class ClassA
{
public:
ClassA(ClassB *p) b(p){}
~ClassA(){delete b;}
ClassB *b;
};
Is this kind of design a good one?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With