To make it simple, anytime you make a new
, you should make a corresponding delete
.
In your case, you have to delete the allocated objects Obj
at latest before your objects Objects
are deleted, which means in the destructor
of Objects
, which also means that you have to keep a way to access to the one
and two
pointers at the destructor (one way might be to make them as a member of Objects
). Your current case fails to do so because one
and two
are local variables and are not pointers.
It may look like the following:
class Objects
{
public:
Objects();
virtual ~Objects();
private:
Obj* one;
Obj* two;
};
Objects::Objects{
one = new Obj;
two = new Obj;
}
Objects::~Objects{
delete one;
delete two;
}
There are some rules you need to be aware of, when coping with resource management and it is the rule of three/five/zero which will guide you to create robust code in terms of resource management.
Another remark:
It might be better to use smart pointers as even with the approach I mentionned in my post, if an exception or a crash happenned before your code executes the delete
lines, you would still have a memory leak as explained here