ordering of constructors

Jay Freeman (saurik) saurik@saurik.com
Fri Apr 9 19:02:00 GMT 2004


Chris:

The standard said "These objects are destroyed in the reverse order of the
completion of their constructors." The "completion", not the "initiation" or
"start" or whatever. If we modify the code again to show this:

#include <iostream>

struct A {
    A() { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};

A &a() {
    static A value;
    return value;
}

struct B {
    B() { a(); std::cout << "B()" << std::endl; }
    ~B() { std::cout << "~B()" << std::endl; }
};

B b;

int main() {
    std::cout << "main()" << std::endl;
    return 0;
}

We get:

A()
B()
main()
~A()
~B()

Which _doesn't_ make much sense ;).

Sincerely,
Jay Freeman (saurik)
saurik@saurik.com

----- Original Message ----- 
From: "Chris Lattner" <sabre@nondot.org>
To: "Jay Freeman (saurik)" <saurik@saurik.com>
Cc: <gcc@gcc.gnu.org>
Sent: Friday, April 09, 2004 12:26 PM
Subject: Re: ordering of constructors


>
> > So in this case, the output should be:
> > main()
> > ~B()
> > ~A()
>
> No, I don't think it should be.  Consider this modified program, which
> just prints out the order of construction as well:
>
> ------------
> #include <stdio.h>
> struct A {
>     A() { printf("A()\n"); }
>     ~A() { printf("~A()\n"); }
> };
>
> A &a() {
>     static A value;
>     return value;
> }
>
> struct B {
>     B() { printf("B()\n"); a(); }
>     ~B() { printf("~B()\n"); }
> };
>
> B b;
>
> int main() {
>     printf("main()\n");
>     return 0;
> }
> --------------
>
> This prints:
>
> B()
> A()
> main()
> ~A()
> ~B()
>
> ... which is what I would expect.  The order of destruction has to be the
> opposite of the order of construction.
>
> -Chris
>
> -- 
> http://llvm.cs.uiuc.edu/
> http://www.nondot.org/~sabre/Projects/



More information about the Gcc mailing list