When does std :: shared_ptr free 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 the signature is MyFunctionas follows:

void MyFunction(const MyClass& my_object)

Full code can be found here.

However, I found that my_object is actually out of scope in the context MyFunction. My thought was that it my_shared_objectwould release its content only after leaving the scope, which means after returning MyFunction. I am not sure that I am either misunderstanding std::shared_ptr, or maybe this is a GCC error.

I think the question boils down to: when I look for std :: shared_ptr, does it guarantee that it std::shared_ptrwill persist until dereferencing is used?

+4
source share
3 answers

Everything that is controlled with the help std::shared_ptrwill be destroyed at the moment when there is no std::shared_ptrneed to approve the claim, all other ways to refer to it do not matter.

And local variables are destroyed only after leaving the corresponding area. Dereferencing a std::shared_ptrdoes not change it.

+5
source

std::shared_ptr ( std::shared_ptr) , , std::shared_ptr, . , std::shared_ptr , , .

, std::shared_ptr , , , MyFunction.

+4

std:: shared_ptr . , . , shared_ptr , . , .

+1
source

Source: https://habr.com/ru/post/1616614/


All Articles