Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference count when returning a shared_ptr

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)...

like image 484
Tony The Lion Avatar asked Oct 11 '10 09:10

Tony The Lion


People also ask

Is shared_ptr reference counting?

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.

Can you return a shared_ptr?

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.

Is shared_ptr reference counting thread safe?

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.

What happens when shared_ptr goes out of scope?

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.


1 Answers

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.)

like image 161
Potatoswatter Avatar answered Sep 19 '22 01:09

Potatoswatter