constructor error with an inherited class

  • Thread starter Thread starter Bruno van Dooren
  • Start date Start date
B

Bruno van Dooren

Hi, i have the following problem:
I have an unmanaged class that is derived from 2 base classes

class A : public B, C
{
...
}

the constructor is something like

A::A() : B(), C()
{
...
}

i was wondering what would happen if the contructor of B or C throws an
exception.
in that case i will never get the pointer to A, so i cannot delete it, but
what if the other constructor
(for example B()) succeeded? will B automatically be deleted (will its
constructor be invoked)? or will there be a memory leak?

kind regards,
Bruno.
 
Bruno said:
Hi, i have the following problem:
I have an unmanaged class that is derived from 2 base classes

class A : public B, C
{
...
}

the constructor is something like

A::A() : B(), C()
{
...
}

i was wondering what would happen if the contructor of B or C throws an
exception.
in that case i will never get the pointer to A, so i cannot delete it, but
what if the other constructor
(for example B()) succeeded? will B automatically be deleted (will its
constructor be invoked)? or will there be a memory leak?

Fully constructed base class and member subobjects will be destroyed.
However, if your ctor does something like this:

// p1 and p2 are X* and Y*
Z()
: p1(new X),
p2(new Y)
{
}

Then if "new Y" throws an exception, you have a problem, because the Z
object is not fully constructed, so its dtor won't be called, and since p1
is a native pointer, its destruction is a no-op. However, if p1 was an
object of a suitable smart pointer type, then p1 would be destroyed and its
dtor called, deleting the object it points to, and everything would be fine.

To finish answering your question, exceptions thrown during the execution of
a new-expression do not normally leak the memory allocated by the new
operator. Instead, an operator delete function which matches the operator
new used by the new-expression is called, and it this operator delete that
is responsible for "undoing" the memory allocation.
 
Back
Top