This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: ordering of constructors
- From: "Jay Freeman \(saurik\)" <saurik at saurik dot com>
- To: "Chris Lattner" <sabre at nondot dot org>
- Cc: <gcc at gcc dot gnu dot org>
- Date: Fri, 9 Apr 2004 12:26:49 -0500
- Subject: Re: ordering of constructors
- References: <Pine.LNX.4.44.0404091224150.28223-100000@nondot.org>
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/