deleting shared memory c++

Soldato
Joined
23 May 2005
Posts
2,964
Location
Auckland, New Zealand
Hi, i've drawna bit of a blank on this one..

say i have an object class like this:

Code:
class Object{

public:
   ...
   ~Object();
   void SetMaterial(Material *m)

protected:
   Material* materialPtr;
};

Object::~Object(){
   if(materialPtr){
      delete materialPtr;
      materialPtr = NULL;
  }
}

void Object::SetMaterial(Material *m){
   materialPtr = m;
}

And I declare two objects with the same material like so:

Code:
Material* Material = new Material();
Object* Object1 = new Object();
Object* Object2 = new Object();

Object1->SetMaterial(Material);
Object2->SetMaterial(Material);

When the objects get destroyed, each object tries to call the material destructor.. breaking the program. How would i fix this? Any help appreciated :)

Joe
 
You can let the creator of the material destroy it (so Object doesnt delete it), or you can ref count the material (i.e. each object calls Inc/DecRef), or you can use a smart pointer to ref count (the last two are similar but subtly different).
 
Back
Top Bottom