Here is my issue:
My bas开发者_Python百科e class has a constructor that takes in a class pointer, if that pointer is NULL, it knows to instance it itself and maintain it.
The problem is, in the base destructor, I have to unregister that pointer with something private of base. So what happens is when I try to make a call to the class pointer in the base destructor and the derived is maintaining it, it has already been freed. So that causes a problem. What could I do?
Thanks
If the base class creates an instance for the pointer, why can't it free it as well? Is there anything stopping you from moving the free into the base destructor?
It's always best to be consistent in terms of who does what, at a certain level of hierarchy- splitting up the same responsibility across several levels of hierarchy will surely lead to problems such as this. Not to mention, if you want to create another class that inherits from base, you will have to re-implement this management in the new class as well, creating code duplication.
The order of constructors and destructors in inheritence is opposite; the base constructor is called before any of it's derived constructors. Upon delete, the inverse happens - the derived class is deleted first.
To solve your problem, could the base destructor not test whether its private instance is not NULL
?
The base class could implement a protected
member function to do the cleanup, then the derived destructor could call this helper function before destroying the resource.
From your description I gather that sometimes the derived class will be in charge of this pointer, and sometimes the base class will be. The simplest solution I can think of is to add a boolean in your base class that will allow you to track who owns the object. If the base class has initialized the pointer, set the boolean to true. Then your destructor can check who owns the object and in turn whether it should clean up.
A better solution would be to use boost:shared_ptr. This is a reference counting pointer abstraction that will automatically cleanup your object when its last reference goes out of scope. With this abstraction you generally don't need to worry about who releases your pointer.
If your constructor allocates memory, the corresponding destructor is responsible for freeing it. If you conditionally allocate memory, then you need to conditionally free it. A Boolean flag would help you determine if allocation occurred.
Another solution is to use a reference counting. At the time of the allocation the reference count shall be 1. If another class has interest in the object, it retains the pointer by increasing the reference count. If a class is no longer interested in the object, it decreases the reference count. When the counter reaches 0, the object must be deleted. shared_ptr is a standard C++ reference counted auto pointer implementation, which works very well in complex mixed ownership situations.
精彩评论