Does the following code mean that when this function returns, the request object inside this class still holds a reference to this object?
boost::shared_ptr<Request> RequestList::GetRequest()
{
boost::mutex::scoped_lock(listmtx);
request = boost::shared_ptr<Request>(new Request());
return request;
}
used:
request = requests->GetRequest(); //Ref count is two on request object when it returns??
even after having completed above assignment, we still have a ref count of two on request
...
where requests is just a RequestList pointer (raw pointer)...
The shared reference counter counts the number of owners. Copying a std::shared_ptr increases the reference count by one. Destroying a std::shared_ptr decreases the reference count by one. If the reference count becomes zero, the resource will automatically be released.
So the best way to return a shared_ptr is to simply return by value: shared_ptr<T> Foo() { return shared_ptr<T>(/* acquire something */); }; This is a dead-obvious RVO opportunity for modern C++ compilers.
A std::shared_ptr consists of a control block and its resource. Yes, the control block is thread-safe; but no, the access to the resource is not thread-safe. That means, modifying the reference counter is an atomic operation and you have the guarantee that the resource will be deleted exactly once.
The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.
request is a private class variable...
Then there are two shared_ptr
objects with a handle to the new Request()
: the one in the calling function and the private class variable. Both legitimately bump the refcount.
Unless there's a reason for the private class variable to exist, eliminate it. At the very least, rename it last_request
, because that's what it really is.
(Of course, when last_request
gets reassigned by another call to GetRequest
, its handle to the previous request goes away.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With