views:

88

answers:

2

Im working on this project,

The problem Im having is that the an object, does not really get deleted when I need it to be because it has a couple of shared pointers pointing to it.

How do I solve this,please help.

+8  A: 

This is by design. As long as an object is owned by one or more shared_ptr smart pointers, it will not be destroyed. Ownership of the object is shared by all of the smart pointers that have ownership and the object can't be destroyed until all of the owners are done with it. This is what shared ownership is.

If you want to be able to destroy the object while there are still some references to it, you can use weak_ptr for those references.

James McNellis
+1 sounds like those hanging refs should be via weak_ptr alright
Steve Townsend
A: 

You can decrease the use_count of a shared_ptr by using its reset() method.

If you do this for every pointer which holds the instance, the last reset() will destroy the object it points to.

shared_ptr<Class> myPointer1( new Class() ); //myPointer holds an instance of Class
shared_ptr<Class> myPointer2 = myPointer1; //use_count == 2
myPointer1.reset(); //use_count == 1
myPointer2.reset(); //instance of class will be destroyed

But you probably have a problem with you design, shared_ptr should automatically go out of focus when certain objects are destroyed or methods end. Perhaps you should have a look at the points where the shared_ptrs still hold pointers to the object and check if they shouldn't hold the object anymore.

MOnsDaR
That won't delete the object if it is shared by other `shared_ptr` instances.
sbi
You're right, just researched this and saw, that I was wrong. I'll edit this out.
MOnsDaR