In the following code, there is a memory leak if Info::addPart1()
is called multiple times by accident:
typedef struct
{
}part1;
typedef struct
{
}
Checking for nonzero pointer before delete is redundant. delete 0
is guaranteed to be a no-op.
A common way to handle this is
delete _ptr1;
_ptr1 = 0;
_ptr1 = new part1;
Zeroing the pointer ensures there won't be any dangling pointers for example in the case part1 construction throws an exception.
On the far extreme of possible ways to deal with memory leaks is the boehm garbage collector, a conservative mark & sweep collector. Interestingly, this can be used in addition to all the good advice offered in other answers.
You should take a look at RAII
Use a smart pointer such as boost:shared_ptr , boost:scoped_ptr is recommended to manage the raw pointer. auto_ptr is tricky to work with, you need pay attention to that.
Option 1: Use Java :)
Option 2: Use auto_ptr
std::auto_ptr<part1> _ptr1;
std::auto_ptr<part2> _ptr2;
public:
addPart1()
{
_ptr1 = auto_ptr<part1>(new part1);
}
...
// no destructor is needed