1 2 3 4 5
|
ClassA::ClassA()
{
if( !myInstanceB ) // This is probably overkill. Old habits...
myInstanceB = new ClassB();
}
|
That's not just overkill.. it's actually flat out incorrect =P
myInstanceB has not been initialized at that point, so there is no way to guarantee it will be null.
More often than not, the above ctor will not allocate anything and will leave myInstaceB as a bad pointer.
EDIT:
This is arguably overkill
1 2 3 4 5 6 7 8
|
ClassA::~ClassA()
{
if( myInstanceB )
{
delete myInstanceB;
myInstanceB = NULL;
}
}
|
For 2 reasons:
1) delete does nothing if the pointer is null, so there's no reason to check for null first (delete already does it)
2) no reason to null the pointer afterwards because this is the dtor and myInstanceB will literally not exist anymore after this function completes.
1 2 3 4
|
ClassA::~ClassA
{
delete myInstanceB;
}
|
This is really all you need.
fstigre wrote: |
---|
What would happen if I don't delete it in the deconstructor, would that be considered a memory leak? |
Yes.
Every
new
that does not have a matching
delete
will leak memory. If you do not delete this in the dtor, then every time you instantiate a ClassA object it will leak a ClassB object.
Furthermore... if you have a pointer in a class... the compiler provided copy constructor and assignment operators
will not work and will cause your program to break if you try to use them.
So if you do this, you really should do one of the following:
1) Write your own copy ctor / assignment operator:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class ClassA
{
public:
ClassA(const ClassA& rhs)
{
myInstanceB = new ClassB( *rhs.myInstanceB );
// ... copy any and all other members here
}
ClassA& operator = (const ClassA& rhs)
{
*myInstanceB = *rhs.myInstanceB;
// ... copy and and all other members here
return *this;
}
//...
|
OR 2) forbid copying by deleting the copy ctor / assignment operator (using the
= delete
syntax if your compiler supports it... or by making them private and not giving them a body if your compiler doesn't)