Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we delete a pointer that is not new/malloc by us?

class ClassA
{
public:
    ClassA(ClassB *p) b(p){}
    ~ClassA(){delete b;}
    ClassB *b;
};

Is this kind of design a good one?

like image 615
qiuxiafei Avatar asked Nov 03 '10 12:11

qiuxiafei


3 Answers

The answer is it depends. You have to make clear who is responsible for the object lifetime.

Also ClassA lacks a user-defined copy-constructor and assignment operator and this can lead to undefined behavior. For example:

ClassA object1( new ClassB() ); //object1 takes ownership of the object
ClassA object2( object1 ); //object2 takes ownership of the same object
// now first object2 is destroyed and deletes the object
// then object1 is destroyed and double-delete happens

so your example is likely not a very good one.

like image 86
sharptooth Avatar answered Oct 20 '22 00:10

sharptooth


Do you mean:

class ClassA  { 
  ClassB *b;  
public: 
  ClassA(ClassB * p) {b = p;} 
  ~ClassA() {delete b;}  
};

This is not good design. The one who creates should be the one who deletes.

like image 26
Bob Yoplait Avatar answered Oct 20 '22 00:10

Bob Yoplait


Usually using pointers in this kind of situation is bad design. In this kind of situation smart pointers are your best friends. However if you have to use pointers then just choose either way and carefully document it

like image 20
Armen Tsirunyan Avatar answered Oct 20 '22 00:10

Armen Tsirunyan