Search code examples
c++pointersshared-ptr

about shared_ptr


Just want to clarify regarding shared_ptr

int main(){
   typedef std::tr1::shared_ptr<Foo> _foo;

   _foo obja(new Foo());
   Foo *objb = obja.get(); 

   // delete objb; //deleting objb will throw double free or corruption
   return 0;
}

In the code above, is there a memory leak if objb is not deleted or freed? In the end, obja will go out of scope and will free itself. Since objb and obja are pointing in the same instance does that mean there's no need in freeing objb?

Is the above the same as this:

Foo *obja = new Foo();
Foo *objb;

objb = obja;
delete obja;

Solution

  • In the code above, is there a memory leak if objb is not deleted or freed?

    No. The Foo object is owned by the obja shared pointer. By doing .get(), you retrieve a "dumb", observing pointer that does not have any influence on the lifetime of the pointed object. You just have to be careful not to dereference it after the pointed object has ceased to exist, or you will get Undefined Behavior.

    Since objb and obja are pointing in the same instance does that mean there's no need in freeing objb?

    There is no need of freing objb because when obja goes out of scope, its destructor will delete the owned object. If you did delete objb, you would get Undefined Behavior by trying to delete an object twice.

    Is the above the same as this:

    I guess one could say so, yes.