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