If my class has a pointer of some sort that can be set by the class clients, how should I deal with deletion?
Example:
class A {
};
class B {
public:
void setA(A* a) {
this->a = a;
}
private:
A* a;
};
How should be the destructor of the class B? Should it delete a? As I see, there are two way a user can set this pointer:
... // Assume B object b being created elsewhere
A aObj;
A* aPtr = new A();
b.setA(&aObj); // It is not OK to use delete, and class member will
// point to invalid memory location once aObj goes out
// of scope
b.setA(aPtr); // Using new will make the pointer available even after
// this block of code
...
So what is the right way of deleting b? Should I always perform a new in my set method?
You, the author of the class, decides of its semantics. Don’t think in terms of pointers, references, and
deletes. Think in terms of design: what’s the relation betweenAandB? What doesBneeds aAfor?Two common types of relation are delegation and composition. Delegation would mean that client code uses the
setAmember to have the instance aware of some otherBinstance that it may use for further uses. Composition would mean that thesetAmember is used to initialize an internal part of the instance.One possible implementation of delegation is using a member pointer. I’d recommend passing a reference to
setAto assign to that pointer; it sidesteps the issue of checking for0and makes it obvious to client code that there is no ownership issue to deal with. This is compatible with polymorphic types.One possible implementation of composition is using a
Amember, and passing by reference to const or by value to assign to it. Another is to use a smart pointer, especially ifAis meant to be used polymorphically. Passing by smart pointer is the simplest thing to do — but you’ll have to check for0and/or document the cast.No matter what you decide to use (which doesn’t have to be in this list anyway), use code as a tool to achieve your purpose or design. Don’t let code dictate your thoughts.
In all my example implementations you don’t have to do anything special in the destructor.