Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does std::shared_ptr release its object?

I'm on Ubuntu 14.04 using GCC 4.8.4 and I have code similar to the following:

std::shared_ptr<MyClass> my_shared_object = set elsewhere...
MyFunction(*my_shared_object);

Where MyFunction's signature looks like this:

void MyFunction(const MyClass& my_object)

The full code can be found here

However, I am finding that my_object actually goes out of scope within the context of MyFunction. My thought was that the my_shared_object will only release its contents once it goes out of scope, meaning after the MyFunction has returned. I am not sure if I am either misunderstanding std::shared_ptr or if maybe this is a GCC bug.

I guess the question boils down to: when I dereference a std::shared_ptr, does that guarantee that the std::shared_ptr will persist as long as the dereference is being used?

like image 374
kip622 Avatar asked Nov 19 '15 19:11

kip622


People also ask

What happens when shared_ptr goes out of scope?

All the instances point to the same object, and share access to one "control block" that increments and decrements the reference count whenever a new shared_ptr is added, goes out of scope, or is reset. When the reference count reaches zero, the control block deletes the memory resource and itself.

What happens when you move a shared_ptr?

By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr . "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).

Why would you choose shared_ptr instead of unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

Why is shared_ptr unique deprecated?

What is the technical problem with std::shared_ptr::unique() that is the reason for its deprecation in C++17? this function is deprecated as of C++17 because use_count is only an approximation in multi-threaded environment.


1 Answers

Whatever is managed by a std::shared_ptr will be destroyed the moment there's no std::shared_ptr left asserting a claim, all other ways to refer to it are irrelevant.

And local variables are only destroyed upon leaving the respective scope. Dereferencing a std::shared_ptr does not modify it in any way.

like image 109
Deduplicator Avatar answered Sep 27 '22 18:09

Deduplicator