I have a class A whose objects store a pointer.
This class's objects will either be used in another class (B)'s constructor which will take ownership of that pointer (thus making the A object useless) or be told that their pointer is useless and that they aren't needed anymore (which means they will free the memory pointed to by the pointer they hold).
So these objects have a pointer and a free
method which deletes that pointer.
My question is, since the objects won't be needed anymore after they're either used by B's constructor or their method free
is used, is it considered bad design / practice to tell B's constructor to also delete the A object it used, and to insert a delete this
instruction at the end of A::free()
? Or should I stick to manually delete those?
A little example:
A* myobj = new A(new Value(12));
B* myfinalobj;
if (is_useful(myobj)) {
myfinalobj = new B(myobj);
delete myobj;
}
else {
myobj->free();
delete myobj;
}
VS
A* myobj = new A(new Value(12));
B* myfinalobj;
if (is_useful(myobj)) {
myfinalobj = new B(myobj); //myobj deletion is done by B::B(A*)
}
else {
myobj->free(); //myobj deletion is done internally by A::free()
}