Noncompliant destruction order for statics


2007-08-16 07:53:39 PM
cppbuilder109
Section 3.6.3 of the C++ language standard states that
"Destructors for initialized objects of static storage duration
(declared at block scope or at namespace scope) are called as a result
of returning from main and as a result of calling exit. These objects
are destroyed in the reverse order of the completion of their
constructor or of the completion of their dynamic initialization. If
an object is initialized statically, the object is destroyed in the
same order as if the object was dynamically initialized."
This appears to be satisfied by Borland C++ Builder 6 if all statics
are compiled in the same translational unit. However, Borland C++
Builder 6 apparently fails to satisfy this if the statics are
distributed over several translation units (which is more common). Did
anyone experience this as well? Is this well known?
Example (compile it with "bcc32 staticdestroy.cpp foo.cpp -o
staticdestroy"):
// staticdestroy.cpp
#include <iostream>
#include <memory>
#include "foo.h"
int main(int argc, char* argv[]) {
static std::auto_ptr<foo>f(new foo);
}
// bar.h
#ifndef BAR_H
#define BAR_H
#include <iostream>
class bar {
public:
bar() : v(2) { std::cout << "bar being created" << std::endl; }
~bar() { std::cout << "bar being destroyed" << std::endl; }
int v;
};
#endif
// foo.h
#ifndef FOO_H
#define FOO_H
#include <iostream>
#include "bar.h"
class foo {
public:
foo() {
std::cout << "foo being created" << std::endl;
std::cout << "foo.b.v is " << b.v << std::endl; }
~foo() { std::cout << "foo being destroyed" << std::endl; }
static bar b;
};
#endif
// foo.cpp
#include "foo.h"
bar foo::b;