Order of destruction

Discussion in 'C++' started by Lilith, Apr 3, 2008.

  1. Lilith

    Lilith Guest

    Does the standard define the order in which objects declared in the
    same scope are destructed when those objects go out of scope? This
    has a bearing on some cleanup work I want to incorporate in one of my

    Lilith, Apr 3, 2008
    1. Advertisements

  2. Lilith

    Martin York Guest

    Reverse order of creation.
    Martin York, Apr 3, 2008
    1. Advertisements

  3. Lilith

    Lilith Guest

    Thank you. That makes it much easier to maintain.
    Lilith, Apr 3, 2008
  4. Lilith

    James Kanze Guest

    Yes and no. The concepts are definitely orthogonal, but for
    historical reasons, in C++, object lifetime, or at least the
    default object lifetime, is partially determined by the scope of
    the object's definition.
    Only within very restricted categories, and with numerous
    exceptions. Reverse order is true for members of a class,
    temporaries whose lifetime hasn't been extended, non-static
    local variables, objects with static lifetime, and I think (but
    I'm not sure) thrown objects. It's trivial, however, to create
    examples where order of destruction is not the reverse of
    construction: anytime a temporary is bound to a const reference,
    for example, or is used to initialize an other object; or between
    static and non-static local variables. E.g.:

    MyClass a ;
    static MyClass b ;

    Order of construction: a, then b. Order of destruction, a, and
    sometime well after leaving f, b. (Throw in a call to exit() at
    the end of f, and the issue becomes even less clear---a will
    never be destructed.)
    James Kanze, Apr 4, 2008
    1. Advertisements

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.