Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice on where to delete a resource in an inheritance hierarchy

Tags:

c++

oop

Consider the following code:

class Base {
protected: 
    int* ptr_;

public:
    virtual ~Base() { /* delete ptr_ ?? */ }    
}

class A : public Base {
public:
    A() { ptr_ = new int; }
    ~A() { /* delete ptr_ ?? */ }
}

I'm having a minor dispute with my colleague.
Which destructor should delete ptr_?
I think it should be in A, because it's where it is allocated.
He thinks it should be in Base, because thats where the pointer is.

Please give possible pitfalls why one method is better than the other (if there is one, and it's not just a matter of taste)

EDIT
Alot of people are questioning the design. In practice, the code is much more complicated, and models an Image processing system involving a few cameras. The role of Base is to manage the resources of the system (A few configurations exist). Class A and other derived types like it decide the configuration of Base and initialize the system to a specific configuration. I guess now you can ask if Inheritance is the right choice over Composition. A is-a Base, just a specific kind, and that is why we chose inheritance. In this case, ptr_ is a pointer to a specific driver of a camera, which will be decided by the derived type, that is why it is allocated there.

like image 485
Itsik Avatar asked Aug 30 '11 07:08

Itsik


1 Answers

Each class should manage its own resources. When you have multiple derived classes, each one must remember to free the pointer. This is bad, since it duplicates code.

If some derived class is allowed not to assign the pointer a fresh value, then set it to zero in the base class constructor. If some derived class should be allowed to assign to the pointer the address of an automatic variable, then review your design.

Use smart pointers to make the problem totally go away (when I grep delete * in my entire codebase, I find no match :)

like image 188
Alexandre C. Avatar answered Oct 27 '22 14:10

Alexandre C.