constructor error with an inherited class

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bruno van Dooren

    #1

    constructor error with an inherited class

    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.


  • Doug Harrison [MVP]

    #2
    Re: constructor error with an inherited class

    Bruno van Dooren wrote:
    [color=blue]
    >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?[/color]

    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.

    --
    Doug Harrison
    Microsoft MVP - Visual C++

    Comment

    Working...