Object construction...

Discussion in 'C++' started by barcaroller, May 10, 2008.

  1. barcaroller

    barcaroller Guest

    At which point is an object considered to be completely constructed?

    X::X()
    {
    // constructor stuff

    throw "Exception"; // premature exit
    }

    X* x;

    try
    {
    x = new X; // is 'x' a complete object?
    }
    catch (...)
    {
    delete x; // is this valid?
    }


    Is it only the throw() that determines if an object has been constructed or
    not?
     
    barcaroller, May 10, 2008
    #1
    1. Advertising

  2. barcaroller

    Guest

    On May 10, 10:24 am, Andy Champ <> wrote:
    > barcaroller wrote:
    > > At which point is an object considered to be completely constructed?

    >
    > > X::X()
    > > {
    > > // constructor stuff

    >
    > > throw "Exception"; // premature exit
    > > }

    >
    > > X* x;


    x must be initialized; otherwise its use is undefined behavior:

    X * x = NULL;

    > > try
    > > {
    > > x = new X; // is 'x' a complete object?
    > > }
    > > catch (...)
    > > {
    > > delete x; // is this valid?
    > > }

    >
    > > Is it only the throw() that determines if an object has been constructed or
    > > not?

    >
    > IIRC it's considered as completely constructed when the constructor
    > exits (successfully).


    That's correct.

    > In this case the delete will give undefined behaviour, because even if
    > I'm subtly wrong about when "construction is complete" you'll never get
    > to the return from the new call after which the assignment to x is made
    > - so x will have an undefined value.


    Correct.

    > I get nervous about exceptions in constructors...


    Yet there is only exceptions to avoid a half constructed object.

    Herb Sutter's Exceptional C++ has been the book that eliminated my
    nervousness in the past. The book presents a number of guidelines
    which results in code that works even if exceptions are thrown.

    One such guideline is to never release resources explicitly in code
    (the idiom is RAII and predates Herb Sutter's book). so the original
    code better be

    SomeSmartPointer x(new X());

    Ali
     
    , May 11, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Anthony
    Replies:
    1
    Views:
    307
    Victor Bazarov
    Sep 23, 2003
  2. Jerivix Entadi
    Replies:
    4
    Views:
    382
    John Harrison
    Feb 23, 2004
  3. newbiecpp

    Object construction

    newbiecpp, Jul 22, 2004, in forum: C++
    Replies:
    2
    Views:
    434
    SaltPeter
    Jul 22, 2004
  4. Ook
    Replies:
    10
    Views:
    559
  5. cantide5ga
    Replies:
    7
    Views:
    391
    cantide5ga
    Oct 23, 2007
Loading...

Share This Page