Destruction order of static objects in C++ - c++

Can I control the order static objects are being destructed?
Is there any way to enforce my desired order? For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static object?

The static objects are destructed in the reverse order of construction. And the order of construction is very hard to control. The only thing you can be sure of is that two objects defined in the same compilation unit will be constructed in the order of definition. Anything else is more or less random.

The other answers to this insist that it can't be done. And they're right, according to the spec -- but there is a trick that will let you do it.
Create only a single static variable, of a class or struct that contains all the other things you would normally make static variables, like so:
class StaticVariables {
public:
StaticVariables(): pvar1(new Var1Type), pvar2(new Var2Type) { };
~StaticVariables();
Var1Type *pvar1;
Var2Type *pvar2;
};
static StaticVariables svars;
You can create the variables in whatever order you need to, and more importantly, destroy them in whatever order you need to, in the constructor and destructor for StaticVariables. To make this completely transparent, you can create static references to the variables too, like so:
static Var1Type &var1(*svars.var1);
VoilĂ  -- total control. :-) That said, this is extra work, and generally unnecessary. But when it is necessary, it's very useful to know about it.

Static objects are destroyed in the reverse of the order in which they're constructed (e.g. the first-constructed object is destroyed last), and you can control the sequence in which static objects are constructed, by using the technique described in Item 47, "Ensure that global objects are initialized before they're used" in Meyers' book Effective C++.
For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static onject?
Ensure that it's constructed before the other static object.
How can I control the construction order? not all of the statics are in the same dll.
I'll ignore (for simplicity) the fact that they're not in the same DLL.
My paraphrase of Meyers' item 47 (which is 4 pages long) is as follows. Assuming that you global is defined in a header file like this ...
//GlobalA.h
extern GlobalA globalA; //declare a global
... add some code to that include file like this ...
//GlobalA.h
extern GlobalA globalA; //declare a global
class InitA
{
static int refCount;
public:
InitA();
~InitA();
};
static InitA initA;
The effect of this will be that any file which includes GlobalA.h (for example, your GlobalB.cpp source file which defines your second global variable) will define a static instance of the InitA class, which will be constructed before anything else in that source file (e.g. before your second global variable).
This InitA class has a static reference counter. When the first InitA instance is constructed, which is now guaranteed to be before your GlobalB instance is constructed, the InitA constructor can do whatever it has to do to ensure that the globalA instance is initialized.

Short answer: In general, no.
Slightly longer answer: For global static objects in a single translation-unit the initialization order is top to bottom, the destruction order is exactly reverse. The order between several translation-units is undefined.
If you really need a specific order, you need to make this up yourself.

Theres no way to do it in standard C++ but if you have a good working knowledge of your specific compiler internals it can probably be achieved.
In Visual C++ the pointers to the static init functions are located in the .CRT$XI segment (for C type static init) or .CRT$XC segment (for C++ type static init) The linker collects all declarations and merges them alphabetically. You can control the order in which static initialization occurs by declaring your objects in the proper segment using
#pragma init_seg
for example, if you want file A's objects to be created before file B's:
File A.cpp:
#pragma init_seg(".CRT$XCB")
class A{}A;
File B.cpp:
#pragma init_seg(".CRT$XCC")
class B{}B;
.CRT$XCB gets merged in before .CRT$XCC. When the CRT iterates through the static init function pointers it will encounter file A before file B.
In Watcom the segment is XI and variations on #pragma initialize can control construction:
#pragma initialize before library
#pragma initialize after library
#pragma initialize before user
...see documentation for more

Read:
SO Initialization Order
SO Solving the Order of Initialization Problem

No, you can't. You should never rely on the other of construction/destruction of static objects.
You can always use a singleton to control the order of construction/destruction of your global resources.

Do you really need the variable to be initialized before main?
If you don't you can use a simple idiom to actually control the order of construction and destruction with ease, see here:
#include <cassert>
class single {
static single* instance;
public:
static single& get_instance() {
assert(instance != 0);
return *instance;
}
single()
// : normal constructor here
{
assert(instance == 0);
instance = this;
}
~single() {
// normal destructor here
instance = 0;
}
};
single* single::instance = 0;
int real_main(int argc, char** argv) {
//real program here...
//everywhere you need
single::get_instance();
return 0;
}
int main(int argc, char** argv) {
single a;
// other classes made with the same pattern
// since they are auto variables the order of construction
// and destruction is well defined.
return real_main(argc, argv);
}
It does not STOP you to actually try to create a second instance of the class, but if you do the assertion will fail. In my experience it works fine.

You can effectively achieve similar functionality by having a static std::optional<T> instead of a T. Just initialize it as you'd do with a variable, use with indirection and destroy it by assigning std::nullopt (or, for boost, boost::none).
It's different from having a pointer in that it has preallocated memory, which is I guess what you want. Therefore, if you destroy it & (perhaps much later) recreate it, your object will have the same address (which you can keep) and you don't pay the cost of dynamic allocation/deallocation at that time.
Use boost::optional<T> if you don't have std:: / std::experimental::.

Related

std::map initialization does not work when using const variables as keys [duplicate]

Once I was reading an awesome C++ FAQ (It is really good!!) and read the topic about how to prevent the static initialization order "fiasco". So the author advises to wrap the static variables into functions, thus to prevent the "fiasco" by maintaining the creation order of variables. But this seems to me a rude workaround. So my question is, is there any modern, more pattern oriented way to prevent this "fiasco" but to wrap the "static stuff" into functions???
The modern, more pattern-oriented way is not to use globals in the first place.
There's no other way around it.
It wouldn't be much of a "fiasco", otherwise!
So my question is, is there any modern, more pattern oriented way to prevent this "fiasco" but to wrap the "static stuff" into functions???
In most cases, you can declare your "global" data in the main function, and use dependency injection to pass it around, where needed. In other words, do not have static state at all.
In practice, you can have situations where static data is needed. If there are no dependencies to other statics, make the static data const/constexpr.
// smart pointer that implements the "Foo" release policy
class FooPointer
{
static const FooPointer NullFoo; // does not depend on other static values
/* ... */
};
In case the static variables do depend on each other, just wrap them in static functions:
// smart pointer that implements the "Foo" release policy
class FooPointer
{
static const FooPointer& NullFoo(); // depends on other static values
/* ... */
};
To summarize:
Most (90%? 99%?) static/global/shared data should be dependency-injected into where it is used, and not created as static at all.
In the rare cases when statics are required for a reason or another and they do not depend on other statics, declare static variables.
In the very rare cases when statics need to be static and they depend on each other, wap them in static methods.
As a rule of thumb, if you have a lot of the second and third cases, you are not doing enough of the first.
The more usual way of addressing the problem is to avoid statics whenever possible - and even more so between objects that rely on construction order.
Then construct objects in the required order. For example, if we have two objects x and y, and construction of y will fail if x has not been constructed, then construct x first and supply it to the constructor (or another member) of y)
SomeObject x;
SomeOtherObject y(x);
or
SomeObject *x = new SomeObject;
SomeOtherObject y = new SomeObject(*x);
(both of the above assume the constructor of y requires a reference).
If you need to share x and y between functions, simply pass them to functions as arguments.
If you must use statics (i.e. you don't want the typing of passing arguments everywhere) make the statics to be pointers, and initialise them once (for example, in main()).
// all source files can use x and y via these declarations (e.g. via a header file)
extern SomeObject *x;
extern SomeOtherObject *y;
// definition in one source file only
SomeObject *x;
SomeOtherObject *y;
int main()
{
x = new SomeObject;
y = new SomeOtherObject(*x);
// call other functions that use x and y.
delete y;
delete x;
}
But, really, it is best to avoid using statics if at all possible.

When does a constructor of a class with static members runs in C++?

I'm new to c++ so i don't know much about it yet
so basically i have this code
header file
class Application{
public:
static Application& getInstance()
{
return *mInstance;
}
Application();
void run();
protected:
static Application* mInstance;
source file
Application* Application::mInstance;
Application::Application()
{
mInstance = this;
}
then i do
Application::getInstance().run();
When does the constructor for Application class runs?
It seems to work in visual studio.
So my question is why does this work?
Why does getInstance does not return a null pointer? since i have never instantiated the class.
Is this code standard?
will this work on any modern c++ compiler?
The constructor of a class belongs to an object, i.e. if it is called explicitly by the code somewhere it creates an object in the memory (on the stack or on the heap). So if you do not call the constructor somewhere it is never executed.
I see only the point why this can run is that you did not specify the initial value of the mInstance pointer. This means that its value is undefined and accidentally can have some valid address. If the run() method does not touch the mInstance object itself your code can run sometimes but sometimes not. This is the problem of uninitialized variables in C++.
But I suggest to follow the right singleton pattern:
1. Initialize mInstance as a nullptr.
2. The getInstance() function should call the constructor if mInstance is nullptr.
(Just a general hint: Avoid passing this in constructor to somewhere else because at that point the object is not fully constructed and in case of multi-thread application it can cause issues.)
The constructor is executed whenever an object is constructed.
Static objects at file scope are constructed before calling main(). However, if you are relying on order of construction of two such static objects (e.g. construction of one relies on the other already being constructed) you potentially have a problem. The order of construction of statics defined in two distinct compilation units (aka source files) is unspecified.
Static objects that are local (e.g. to a function) are constructed as control passes through their declaration .... typically as their function is called for the first time.

Global variable inside cpp file

I have a global variable inside an anonymous namespace.
namespace {
std::unordered_map<std::string, std::string> m;
}
A::A() { m.insert(make_pair("1", "2")); } // crasches
void A::insert() { m.insert(make_pair("1", "2")); } // ok
If try to use the map inside the constructor I get Access violation reading location.
But if I use it after A has been initialized it works.Is this behavior correct?
What is the scope of the A object whose constructor invocation is causing the crash?
There are no guarantees as to the order that static initializers are executed, so that if your A object is also a global or static (as m is), it's quite possible that m does not exist yet in terms of being a validly constructed object, which would mean that your call to std::unordered_map::insert() would be invoked on uninitialized memory, thus leading to your crash.
A solution is to make sure that all of your A instances that depend on m are constructed explicitly by you and not statically/globally (or as the commenter added, if they are in the same TU, to order them properly), or to change the structure of A such that you can call a function on an instance later in order to do the insert. Whether or not this is a valid solution depends more on the overarching usage of A.
You are probably creating a class of type A in a static context somewhere in your application, ie before your main() function is executed, and therefore before m has been initialized.

How to ensure Singleton is not destroyed prematurely?

In my project, I'm working with about 4 singletons made the Scott Meyer's way. One of them:
LevelRenderer& LevelRenderer::Instance()
{
static LevelRenderer obj;
return obj;
}
Now two of those Singletons, LevelRenderer and LevelSymbolTable interact with each other. For example, in this method:
void LevelRenderer::Parse(std::vector<std::string>& lineSet)
{
LevelSymbolTable& table = LevelSymbolTable::Instance();
/** removed code which was irrelevant **/
// for each line in lineSet
BOOST_FOREACH(std::string line, lineSet)
{
// for each character in the line
BOOST_FOREACH(char sym, line)
{
/** code... **/
// otherwise
else
{
sf::Sprite spr;
// Used LevelSymbolTable's Instance here...
table.GenerateSpriteFromSymbol(spr, sym);
// ^ Inside LevelRenderer
/** irrelevant code... **/
}
}
}
}
Now, although the problem hasn't occurred yet. The thing I am afraid of is, what if the LevelSymbolTable instance is already destroyed before I call GenerateSpriteFromSymbol ?
Since I used the Scott Meyer way, the Singleton's instance was allocated by the stack. Hence is is guaranteed to be destroyed using the last created first destroyed rule. Now if LevelSymbolTable's Instance is created after LevelRenderer's Instance, it will be destroyed before LevelRenderer's Instance, right? So then, if I call a method of LevelSymbolTable inside LevelRenderer (especially in LevelRenderer's destructor), I will be treading on undefined behaviour land.
As I said before, this problem hasn't actually occurred while debugging, and is purely my assumption and guess-work. So, is my conclusion correct? Is LevelSymbolTable liable to be destroyed before LevelRenderer. If so, is there any way out of this mess?
You don't have to worry about anything here.* The static keyword guarantees that it is available from when it is initialized to when the program exits. So, you can make a call to a static variable at any point after it has been initialized.
Also, you have a reference to LevelSymbolTable, not a local variable. This is what the ampersand after the class name means. So you can use it locally, but it's really "referring to" the true object which exists somewhere else. So, when the method exits, the reference will go out of scope but the object it refers to will not.
*Well, you may have to worry about one thing. In a destructor, you should just be cleaning up any memory or file references or other things of that nature you have a handle on. I don't know why you would be calling other objects in a destructor.
Define ownership relation between the objects. Either have LevelSymbolTable as member of LevelRenderer:
class LevelRenderer {
LevelSymbolTable symbolTable;
public:
static LevelRenderer& getInstance();
~LevelRenderer() { /* can use symbolTable here */ }
};
Or create one singleton Level that contains both SymbolTable and Renderer:
class Level {
SymbolTable symbolTable;
Renderer levelRenderer; // note the order here
public:
static Level& getInstance();
private:
/* have LeverRenderer save reference to symbol table,
now renderer can use symbol table anywhere */
Level() : levelRenderer(symbolTable)
{ /* ... */ }
};
EDIT: Or get rid of singletons alltogether. See why singletons are bad. I don't know the structure of your application, but from what I see, you could have Level as a normal class that knows how to render itself and has its symbol table. And have its lifetime connected to the level it is supposed to represent in the application.
Static instances will be created at the beginning of the program (before main) and cleaned up at the end (after main), and you can't rely on any particular order in which they are cleaned up. That is, if you have two instances (let's just make them globals for the sake of simplicity)
class one {
one() {}
~one() {}
};
class two {
two() {}
~two() {}
};
one the_one;
two the_other;
int main() {
...
return 0;
}
You cannot and should not make assumptions about the_one being active in the constructor or destructor of the_other. (And vice versa.)
You can, however, rely on them both being active in any other member function, and within main itself.
The scenario you raise in your question is unlikely to occur, because Parse is probably being called while the program is still active. Only when the program is about to exit would destructors be called.
In you comments, you indicate a slightly different worry, which is global destructor interdependency. This might actually occur if you have global objects that register themselves with some global container. You might expect that objects would remove themselves from the container, and that the container would eject objects.
One way to deal with this is to allow the container to take ownership of the objects that register with it. This means that what gets registered with the global container are dynamically allocated instances, rather than your Scott Meyer's singleton instances. Then, the global container would take charge of cleaning up the registered items when its global destructor is called.

Nifty/Schwarz counter, standard compliant?

I had a discussion this morning with a colleague about static variable initialization order. He mentioned the Nifty/Schwarz counter and I'm (sort of) puzzled. I understand how it works, but I'm not sure if this is, technically speaking, standard compliant.
Suppose the 3 following files (the first two are copy-pasta'd from More C++ Idioms):
//Stream.hpp
class StreamInitializer;
class Stream {
friend class StreamInitializer;
public:
Stream () {
// Constructor must be called before use.
}
};
static class StreamInitializer {
public:
StreamInitializer ();
~StreamInitializer ();
} initializer; //Note object here in the header.
//Stream.cpp
static int nifty_counter = 0;
// The counter is initialized at load-time i.e.,
// before any of the static objects are initialized.
StreamInitializer::StreamInitializer ()
{
if (0 == nifty_counter++)
{
// Initialize Stream object's static members.
}
}
StreamInitializer::~StreamInitializer ()
{
if (0 == --nifty_counter)
{
// Clean-up.
}
}
// Program.cpp
#include "Stream.hpp" // initializer increments "nifty_counter" from 0 to 1.
// Rest of code...
int main ( int, char ** ) { ... }
... and here lies the problem! There are two static variables:
"nifty_counter" in Stream.cpp; and
"initializer" in Program.cpp.
Since the two variables happen to be in two different compilation units, there is no (AFAIK) official guarantee that nifty_counter is initialized to 0 before initializer's constructor is called.
I can think of two quick solutions as two why this "works":
modern compilers are smart enough to resolve the dependency between the two variables and place the code in the appropriate order in the executable file (highly unlikely);
nifty_counter is actually initialized at "load-time" like the article says and its value is already placed in the "data segment" in the executable file, so it is always initialized "before any code is run" (highly likely).
Both of these seem to me like they depend on some unofficial, yet possible implementation. Is this standard compliant or is this just "so likely to work" that we shouldn't worry about it?
I believe it's guaranteed to work. According to the standard ($3.6.2/1): "Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place."
Since nifty_counter has static storage duration, it gets initialized before initializer is created, regardless of distribution across translation units.
Edit: After rereading the section in question, and considering input from #Tadeusz Kopec's comment, I'm less certain about whether it's well defined as it stands right now, but it is quite trivial to ensure that it is well-defined: remove the initialization from the definition of nifty_counter, so it looks like:
static int nifty_counter;
Since it has static storage duration, it will be zero-initialized, even without specifying an intializer -- and removing the initializer removes any doubt about any other initialization taking place after the zero-initialization.
I think missing from this example is how the construction of Stream is avoided, this often is non-portable. Besides the nifty counter the initialisers role is to construct something like:
extern Stream in;
Where one compilation unit has the memory associated with that object, whether there is some special constructor before the in-place new operator is used, or in the cases I've seen the memory is allocated in another way to avoid any conflicts. It seems to me that is there is a no-op constructor on this stream then the ordering of whether the initialiser is called first or the no-op constructor is not defined.
To allocate an area of bytes is often non-portable for example for gnu iostream the space for cin is defined as:
typedef char fake_istream[sizeof(istream)] __attribute__ ((aligned(__alignof__(istream))))
...
fake_istream cin;
llvm uses:
_ALIGNAS_TYPE (__stdinbuf<char> ) static char __cin [sizeof(__stdinbuf <char>)];
Both make certain assumption about the space needed for the object. Where the Schwarz Counter initialises with a placement new:
new (&cin) istream(&buf)
Practically this doesn't look that portable.
I've noticed that some compilers like gnu, microsoft and AIX do have compiler extensions to influence static initialiser order:
For Gnu this is: Enable the init-priority with the -f flag and use __attribute__ ((init_priority (n))).
On windows with a microsoft compiler there is a #pragma (http://support.microsoft.com/kb/104248)