I have a program doing something like the following:
class SomeObject{}
{
void function(int x, int y);
void function(SomeOtherObject *z);
SomeOtherObject *ptrToObj;
}
SomeObject::function(int x, int y)
{
ptrToObj = new SomeOtherObject(x, y);
}
SomeObject::function(SomeOtherObject *z)
{
ptrToObj = z;
}
My problem is that I don’t know the best way to handle deleting that new object when I want to get rid of or initialize an instance of SomeObject, since I can’t count on it actually having been made by SomeObject. (a manager is handling the deletion if SomeObject is passed a pointer)
Options I thought of:
- Copy object and point to that. (It seems messy to have two copies, though the object isn’t that large)
- Make a boolean that is set if the object needs to be deleted. (this is just sort of weird and hacky)
- Make another pointer to hold the object created by SomeObject, point ptrToObj to that pointer instead when it is assigned. (so basically, you know the second pointer can safely be deleted if it isn’t NULL)
- Implement a ref-counting pointer. (this is a little more than I wanted to get into for this)
I did the third one, but I know there must be a better way to handle this problem!
Use a
shared_ptr, either the one from Boost or the one in a recent C++(0x) library.shared_ptrdoes reference counting for you.