So say I have a class like this:
class A {
public:
A( SomeHugeClass* huge_object)
: m_huge_object(huge_object) {}
private:
SomeHugeClass* m_huge_object;
};
If someone uses the constructor like this:
A* foo = new A(new SomeHugeClass());
Who’s responsibility is it to call delete on the object newed in the constructor? In this case, the scope in which the A constructor was called can only delete foo since the SomeHugeClass is anonymous.
However, what if someone uses the constructor like this?
SomeHugeClass* hugeObj = new SomeHugeClass();
A* foo = new A(hugeObj);
Then, the caller can call delete hugeObj at some point, right?
Does this implementation of A leak memory on destruction?
I’m working on a project with a lot of object composition done this way and as much as I would love to use smart pointers, I have to talk to the project leads about changing old code to take advantage of that before I can.
I try to follow this simple rule whenever it is possible: The one who calls
newshould calldeleteas well. Otherwise the code soon becomes too messy to keep track of what is deleted and what is not.In your case, if A::A receives the pointer, it must not delete it. Think of this simple case:
Class A can not know who else is using that pointer!
If you want class A to take care of the pointer, it should create it itself.
Of course, you could handle both cases, but that might be an overkill, something like this: