Question

I am new to smart pointers. However, I have a basic understanding of it. What I've observed is that it is necessary for the smart pointers to get destroyed in the reverse order of their creation or else the smart pointers may misbehave. Consider the below situation:

sharedPtr<abc> my_ptr(new abc); //smart pointer created. Instance counter = 1.
func1(my_ptr);                  //copy constructor in smart pointer called. Instance    counter=2
func2(my_ptr);                  //copy constructor in smart pointer called. Instance counter=3
func3(my_ptr);                  //copy constructor in smart pointer called. Instance counter=4

Now, isn't it necessary that func3() exits first followed by func2(), func1() and finally my_ptr.

Question: What if my_ptr goes out of scope first (& hence tries to delete abc), with func1(), func2() and func3() still referring to abc (through smart pointers) ?

Was it helpful?

Solution

Actually, what you observed is wrong.

The point of smart pointer is to remove the responsibility of destroying the object. That means that the object will be delete when the reference count reach 0: it doesn't matter which pointer is destructed first.

In your case, this would be when my_ptr goes out of scope (assuming you don't make and keep a copy in one your func().

This is what the reference counter should be:

{
sharedPtr<abc> my_ptr(new abc); //smart pointer created. Ref counter = 1.
func1(my_ptr);                  // Ref counter=2 while in func1
// Ref count is 1 again.
func2(my_ptr);                  // Ref counter=2 while in func2
// Ref count is 1 again.
func3(my_ptr);                  // Ref counter=2 while in func3
// Ref count is 1 again.
} // my_ptr goes out of scope, ref count reach 0, and abc is deleted.

OTHER TIPS

I don't know about your custom sharedPtr, but for the standard std::shared_ptr it works like (from the linked reference):

The object is destroyed and its memory deallocated when either of the following happens:

  • the last remaining shared_ptr owning the object is destroyed.

  • the last remaining shared_ptr owning the object is assigned another pointer via operator=() or reset().

So for std::shared_ptr you can pass it around or make as many copies as you want, the order of destruction of those copies will not matter.

What I've observed is that it is necessary for the smart pointers to get destroyed in the reverse order of their creation

Well, the sole reason for existence of shared smart pointers is that one should not care when they get destroyed. When the last shared pointer gets destroyed it destroys the object, as in "the last person to leave turns the light off."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top