Bug in destructor ordering?
Martin Sebor
sebor@roguewave.com
Fri Nov 3 11:17:00 GMT 2000
"Lassi A. Tuura" wrote:
>
> Using egcs-1.1.2, I am seeing a problem with destructor ordering on an
> Intel RedHat 6.1 Linux -- but not on RedHat 5.1. Basically,
> function-local static variable seems to get destructed too early. An
> example problem is below, first with the output I expected, and then the
> wrong behaviour (X::~X gets invoked too early). Does anybody have any
> idea if this is a bug in the compiler or elsewhere in the system
> (glibc?). If in the compiler, can anyone verify it has it been fixed in
> later versions such 2.95.x?
I can verify that it's a bug. From 3.6.3, p1: "...objects [with static
storage duration] are destroyed in the reverse order of the completion
of their constructor or of the completion of their dynamic
initialization. ..."
The expected output (produced when compiled with EDG eccp 2.44 or HP aCC
3.25) is
Y::Y
f()
X::X
main
Y::~Y
f()
X::~X
I can also confirm that the bug still exists in 2.95.2 and in
gcc-20001002.
>
> Any suggestions for a solution or a work-around would be greatly
> appreciated!
Unfortunately, replacing the static local with a pointer to a global as
in the modified example below still doesn't work correctly (I've
included the source as another testcase). You can achieve the correct
behavior by setting a flag in Y::~Y() but that's probably not what you
want.
Regards
Martin
#include <stdio.h>
#include <stdlib.h>
struct X {
X (void) { printf("X::X\n"); }
~X (void) { printf("X::~X\n"); }
};
X *x;
extern "C" void delete_x ()
{
printf ("delete_x()\n");
delete x;
x = 0;
}
X &f (void) {
printf ("f()\n");
if (!x)
atexit (delete_x);
x = new X;
return *x;
}
struct Y {
Y (void) { printf("Y::Y\n"); f(); }
~Y (void) { printf("Y::~Y\n"); f(); }
};
Y y;
int main (int, char **) {
fprintf(stdout, "main\n");
return 0;
}
output:
Y::Y
f()
X::X
main
delete_x()
X::~X
Y::~Y
f()
X::X
delete_x()
X::~X
expected:
Y::Y
f()
X::X
main
Y::~Y
f()
X::X
delete_x()
X::~X
More information about the Gcc-bugs
mailing list