In the following code, there is a memory leak if Info::addPart1()
is called multiple times by accident:
typedef struct
{
}part1;
typedef struct
{
}part2;
class Info
{
private:
part1* _ptr1;
part2* _ptr2;
public:
Info()
{
_ptr1 = _ptr2 = NULL;
}
~Info()
{
delete _ptr1;
delete _ptr2;
}
addPart1()
{
_ptr1 = new part1;
}
addPart2()
{
_ptr2 = new part2;
}
};
Info _wrapper;
_wrapper.addPart1();
_wrapper.addPart2();
Is there a C++ idiom to handle this problem ?
I could rewrite addPart1
and addPart2
like this to defend the MLK
addPart1()
{
if(_ptr1 != NULL) delete _ptr1;
_ptr1 = new part1;
}
Is that a good solution?