This is the mail archive of the
cygwin
mailing list for the Cygwin project.
C++ static destructors run in wrong order
- From: "William M. (Mike) Miller" <william dot m dot miller at gmail dot com>
- To: cygwin at cygwin dot com
- Date: Wed, 11 May 2005 17:45:50 -0400
- Subject: C++ static destructors run in wrong order
- Reply-to: "William M. (Mike) Miller" <william dot m dot miller at gmail dot com>
I mentioned this at the tail end of the thread on static destructors
not running, but since I got no reaction I guess it was probably
overlooked there.
As noted by Christopher Faylor, the May 10 snapshot fixes the
problem of destructors for static objects not being run when
main() returns. However, it does not fix a problem that was also
introduced in 1.5.16, namely, that destructors for static objects
run in the wrong order. The C++ Standard says that such
destructors run in the inverse order of their constructors, and
that was the case prior to 1.;5.16. However, as demonstrated
by the following sample program, global static objects are now
destroyed before local static objects, ignoring their order of
construction:
#include <stdio.h>
#include <stdlib.h>
struct A {
int i;
A(int p) : i(p) { printf("A::A(%d)\n", i); }
~A() { printf("A::~A for %d\n", i); }
};
A a(1);
void f() {
static A a(3);
}
main () {
static A a(2);
printf("main\n");
f();
exit(0);
}
This now prints
A::A(1)
A::A(2)
main
A::A(3)
A::~A for 1
A::~A for 3
A::~A for 2
"A::~A for 1" should be last.
--
William M. (Mike) Miller | Edison Design Group
william.m.miller@gmail.com
--
Unsubscribe info: http://cygwin.com/ml/#unsubscribe-simple
Problem reports: http://cygwin.com/problems.html
Documentation: http://cygwin.com/docs.html
FAQ: http://cygwin.com/faq/