When do function-level static variables get allocated/initialized? - c++

I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.
int globalgarbage;
unsigned int anumber = 42;
But what about static ones defined within a function?
void doSomething()
{
static bool globalish = true;
// ...
}
When is the space for globalish allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when doSomething() is first called?

I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2.
include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const char *name)
: _name(name)
{
cout << _name << " created" << endl;
}
~test()
{
cout << _name << " destroyed" << endl;
}
string _name;
};
test t("global variable");
void f()
{
static test t("static variable");
test t2("Local variable");
cout << "Function executed" << endl;
}
int main()
{
test t("local to main");
cout << "Program start" << endl;
f();
cout << "Program end" << endl;
return 0;
}
The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output:
global variable created
local to main created
Program start
static variable created
Local variable created
Function executed
Local variable destroyed
Program end
local to main destroyed
static variable destroyed
global variable destroyed

Some relevant verbiage from C++ Standard:
3.6.2 Initialization of non-local objects [basic.start.init]
1
The storage for objects with static storage
duration (basic.stc.static) shall be zero-initialized (dcl.init)
before any other initialization takes place. Objects of
POD types (basic.types) with static storage duration
initialized with constant expressions (expr.const) shall be
initialized before any dynamic initialization takes place.
Objects of namespace scope with static storage duration defined in
the same translation unit and dynamically initialized shall be
initialized in the order in which their definition appears in
the translation unit. [Note: dcl.init.aggr describes the
order in which aggregate members are initialized. The
initialization of local static objects is described in stmt.dcl. ]
[more text below adding more liberties for compiler writers]
6.7 Declaration statement [stmt.dcl]
...
4
The zero-initialization (dcl.init) of all local objects with
static storage duration (basic.stc.static) is performed before
any other initialization takes place. A local object of
POD type (basic.types) with static storage duration
initialized with constant-expressions is initialized before its
block is first entered. An implementation is permitted to perform
early initialization of other local objects with static storage
duration under the same conditions that an implementation is
permitted to statically initialize an object with static storage
duration in namespace scope (basic.start.init). Otherwise such
an object is initialized the first time control passes through its
declaration; such an object is considered initialized upon the
completion of its initialization. If the initialization exits by
throwing an exception, the initialization is not complete, so it will
be tried again the next time control enters the declaration. If control re-enters the declaration (recursively) while the object is being
initialized, the behavior is undefined. [Example:
int foo(int i)
{
static int s = foo(2*i); // recursive call - undefined
return i+1;
}
--end example]
5
The destructor for a local object with static storage duration will
be executed if and only if the variable was constructed.
[Note: basic.start.term describes the order in which local
objects with static storage duration are destroyed. ]

The memory for all static variables is allocated at program load. But local static variables are created and initialized the first time they are used, not at program start up. There's some good reading about that, and statics in general, here. In general I think some of these issues depend on the implementation, especially if you want to know where in memory this stuff will be located.

The compiler will allocate static variable(s) defined in a function foo at program load, however the compiler will also add some additional instructions (machine code) to your function foo so that the first time it is invoked this additional code will initialize the static variable (e.g. invoking the constructor, if applicable).
#Adam: This behind the scenes injection of code by the compiler is the reason for the result you saw.

I try to test again code from Adam Pierce and added two more cases: static variable in class and POD type. My compiler is g++ 4.8.1, in Windows OS(MinGW-32).
Result is static variable in class is treated same with global variable. Its constructor will be called before enter main function.
Conclusion (for g++, Windows environment):
Global variable and static member in class: constructor is called before enter main function (1).
Local static variable: constructor is only called when execution reaches its declaration at first time.
If Local static variable is POD type, then it is also initialized before enter main function (1).
Example for POD type: static int number = 10;
(1): The correct state should be: "before any function from the same translation unit is called". However, for simple, as in example below, then it is main function.
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const char *name)
: _name(name)
{
cout << _name << " created" << endl;
}
~test()
{
cout << _name << " destroyed" << endl;
}
string _name;
static test t; // static member
};
test test::t("static in class");
test t("global variable");
void f()
{
static test t("static variable");
static int num = 10 ; // POD type, init before enter main function
test t2("Local variable");
cout << "Function executed" << endl;
}
int main()
{
test t("local to main");
cout << "Program start" << endl;
f();
cout << "Program end" << endl;
return 0;
}
result:
static in class created
global variable created
local to main created
Program start
static variable created
Local variable created
Function executed
Local variable destroyed
Program end
local to main destroyed
static variable destroyed
global variable destroyed
static in class destroyed
Anybody tested in Linux env ?

Or is it initialized when doSomething() is first called?
Yes, it is. This, among other things, lets you initialize globally-accessed data structures when it is appropriate, for example inside try/catch blocks. E.g. instead of
int foo = init(); // bad if init() throws something
int main() {
try {
...
}
catch(...){
...
}
}
you can write
int& foo() {
static int myfoo = init();
return myfoo;
}
and use it inside the try/catch block. On the first call, the variable will be initialized. Then, on the first and next calls, its value will be returned (by reference).

Static variables are allocated inside a code segment -- they are part of the executable image, and so are mapped in already initialized.
Static variables within function scope are treated the same, the scoping is purely a language level construct.
For this reason you are guaranteed that a static variable will be initialized to 0 (unless you specify something else) rather than an undefined value.
There are some other facets to initialization you can take advantage off -- for example shared segments allow different instances of your executable running at once to access the same static variables.
In C++ (globally scoped) static objects have their constructors called as part of the program start up, under the control of the C runtime library. Under Visual C++ at least the order that objects are initialized in can be controlled by the init_seg pragma.

In the following code it prints Initial = 4 which is the value of static_x as it is implemented in the compiling time.
int func(int x)
{
static int static_x = 4;
static_x = x;
printf ("Address = 0x%x",&static_x ); // prints 0x40a010
return static_x;
}
int main()
{
int x = 8;
uint32_t *ptr = (uint32_t *)(0x40a010); // static_x location
printf ("Initial = %d\n",*ptr);
func(x);
return 0;
}

Related

Why is the order of destruction same as order of construction, with static object (C++)?

The code is :
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "A::A" << endl; }
~A() { cout << "A::~" << endl; }
};
class B
{
public:
B() { cout << "B::B" << endl; }
~B() { cout << "B::~" << endl; }
};
int main()
{
B b;
static A a;
return 0;
}
The output is :
B::B
A::A
B::~
A::~
The scope of non-static object b and the scope of static object a ends at the end of main() function.
Question : Why is the order of constructors is same as the order of destructors ?
Static local variables will be destroyed at program exit.
The destructor for a block-scope static variable is called at program exit, but only if the initialization took place successfully.
So b will be destoryed firstly at the end of main(), a will be destroyed after that.
For the initialization,
are initialized the first time control passes through their declaration
So b will be initialized firstly in main(), then a gets initialized.
Because they have different lifespans. A is declared as function-local static variable.
Object created by declaration of automatic function-local variable got lifespan which begins before any use of that object and ends with the most nested code block (braces block) containing that declaration. In your case that's function main() body.
Object created by declaration of static function-local variable begins to exist after execution flow had entered the most nested code block containing that declaration and before any use of that object.
It got process-wide life span (stops to exist at std::atexit()), which happens after the function main() will be exited.
SO they are created in this particular case in order of declaration, but A will get destroyed way later. If your function was called twice, you'd see that B would be created twice but A only once. If function's flow would somehow omit either declaration, by if() statement or by returning early, the order of their creation of would change or both may be omitted.
It's implementation specific detail, but usually destruction of function-local statics implemented in same way as destruction of global objects, by call to a library function that lies under implementation of std::atexit, adding the address of destructor bound with value of pointer to object itself, but the execution may be concurrent (or may be not) with result of user's calls of std::atexit.
As addition to already existing answers, lets take a more phenomenological approach. Consider a small change on your example:
void foo() {
B b;
static A a;
}
int main() {
foo();
foo();
}
I assume you know that a is initialized only once and on the second call we get the exact same object a, because it is declared as static. Hence, it cannot be destroyed during or directly after the first call to foo. The expected first part of the output is
B::B // first call to foo()
A::A
B::~
B::B // second call to foo()
// no second call to A::A !
B::~
a can only be destroyed when your program terminates, otherwise you could not "reuse" it when calling the function again (thats why I had to modify the example, you cannot call main). As other answers explain in great detail, this happens after main returns. Hence last line of output will be
A::~

why static variable is allocated when program starts but initialize later?

I'm new here, I see Static variables in a function are initialized before the function is called for the first time., but I still don't know why it doesn't call the constructor before the function starts?
class Base
{
public:
Base();
~Base();
private:
};
Base::Base()
{
cout << "I'm Base" << endl;
}
Base::~Base()
{
}
int main()
{
cout << "start program!" << endl;
static Base b;
return 0;
}
When are static function variables allocated?, I think the case is almost the same with me..
Any help will be appreciated ^_^
Not quite. Static variables are initialised the first time they are encountered, which of course is not necessarily at the start of a function.
Objects with static storage duration have two phases of initialisation: Static phase and dynamic phase. Some static variables don't have dynamic initialisation at all. Those objects that do have dynamic initialisation are initially statically zero-initialised.
The static phase of initialisation happens when the program starts, before anything else. Thus, memory must also have been allocated before anything else.
The dynamic phase of initialisation cannot be instantaneous. Dynamic initialisation may have dependencies on initialisation of other static objects. Some objects are necessarily initialised before other objects. This is why dynamic initialisation happens after allocation.
For namespace scope variables with static storage, their dynamic initialisation happens either before main, or it may be deferred later in which case it happens before anything from that same translation unit is accessed or called (in practice, deferral happens when dynamic loading is involved).
For static local variables...
Static variables in a function are initialized before the function is called for the first time
Not exactly. Their dynamic initialisation always happens exactly when execution reaches them for the first time. That is always after the function is called; not before. For example:
void foo(bool bar)
{
if (bar) {
static T var;
}
}
var will not be initialised even when the function is called, if the provided argument is false.
The order of dynamic initialisation across translation units is unspecified. This would otherwise make it impossible to safely rely on initialisation of objects with static storage from other translation units, but the "initialisation on first use" behaviour of static local variables is a feature that allows exact control over the order of their initialisation, making it possible to rely on their initialisation even across translation unit boundaries.
I think, based on your comments, that the detail you are missing is that there are both global and local static variables.
Global static variables are initialized when the program is first loaded. Edit: Apparently this is not required behavior (though it is the most common) - initialization is allowed to be delayed. See comment by #walnut.
Example:
int main()
{
std::cout << "start program!" << std::endl;
return 0;
}
static Base b;
Output:
I'm Base
start program!
While static variables in functions are initialized the first time control passes over them. Example:
int main()
{
std::cout << "start program!" << std::endl;
static Base b;
return 0;
}
Output:
start program!
I'm Base
I have added a second example, as per #EvilTeach's comment, to show how the static is only initialized a single time despite multiple functioncalls. Also, added guard (from #eerorika's answer) to show how initialization only happens when execution actually reaches the variable.
void testFunc(bool test)
{
std::cout << "testFunc called with: " << test << std::endl;
if (test)
static Base b;
}
int main()
{
testFunc(false);
testFunc(true);
testFunc(true);
return 0;
}
Output:
testFunc called with: 0
testFunc called with: 1
I'm Base
testFunc called with: 1

How does program know if static variable needs to be initialized? [duplicate]

This question already has answers here:
Why does initialization of local static objects use hidden guard flags?
(2 answers)
Closed 4 years ago.
As in the title - how does program know, that foo is already initialized when function is called second time:
int getFoo()
{
static int foo = 30;
return foo;
}
int main()
{
getFoo();
getFoo();
}
I want to know, whether the program stores some additional information about which static variable was already initialized.
Edit:
I found an answer here:
Why does initialization of local static objects use hidden guard flags?
Like I guessed - most compilers store additional "guard variable".
Have a look at [stmt.dcl]/4:
Dynamic initialization of a block-scope variable with static storage duration or thread storage duration is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.94 If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
You have to be careful here. Primitive statics are initialised at compile time (as long as the initialisation value is a compile-time contant, as Peter points out), so in your example, GetFoo just, in effect, returns a constant.
HOWEVER...
statics which initialise an object (or initialise a primitive by calling a function) perform said initialisation when the scope in which they are declared is entered for the first time.
Furthermore, as of C++ 11 this has to be done in a threadsafe way, which generates a lot of extra code (although not much runtime overhead, after the first time through) and that might be an issue on, say, a micro-controller where code size often matters.
Here's a concrete example:
#include <iostream>
struct X
{
X () { std::cout << "Initialising m\n"; m = 7; }
int m;
};
void init_x ()
{
static X x;
}
int main () {
std::cout << "main called\n";
init_x ();
std::cout << "init_x returned\n";
}
Output:
main called
Initialising m
init_x returned
Live demo: https://wandbox.org/permlink/NZApcYYGwK36vRD4
Generated code: https://godbolt.org/z/UUcL9s

Destruction of static member in a class with global instance

I have a class with a static non-primitive member. For example:
class SomeObject
{
... // something that will be destroyed in destructor,
// like an array pointer.
public:
SomeObject();
~SomeObject();
};
class MyClass
{
static SomeObject m_object;
public:
MyClass();
~MyClass(); // this will access m_object
static bool SetupStaticMember();
};
/// Implementation of SomeObject and MyClass ///
SomeObject MyClass::m_object;
bool dummy = MyClass::SetupStaticMember(); // Setup the values in m_object, for example,
// allocate memory that will be released in ~SomeObject().
MyClass g_my_global_class;
g_my_global_class is declared as global variable, so it's destructor is called after leaving main().
However, MyClass::m_object is static, so it will also be destroyed after main().
Is there any guarantee that ~MyClass() will execute before ~SomeObject() from MyClass::m_object? In other words, when the destructor of a global class instance is called, can I assume that the static members of this class are still there to be accessed, or does this depend on construction/destruction orders?
If the codes are written in this order, I think that g_my_global_class is constructed later, so it should be destructed first. Do things change if the line
MyClass g_my_global_class;
moves to another .cpp file and its file name causes the order to change?
First,
bool dummy = MyClass::InitStaticMember(); // m_object is initialized here
Doesn't actually intialize the static member. That happens at the line before
SomeObject MyClass::m_object;
So since you essentially have
SomeObject MyClass::m_object;
MyClass g_my_global_class;
and since objects are destroyed in the reverse order then g_my_global_class is destroyed before MyClass::m_object.
Now, if you move MyClass g_my_global_class; to a different translation unit then all bets are off. The ordering is only guaranteed in a single translation unit.
Is there any guarantee that ~MyClass() will execute before ~SomeObject() from MyClass::m_object?
Yes. Objects in static storage are destroyed reverse order of initialization.
Statically initialized objects such as MyClass::m_object and g_my_global_class are initialized in order of definition. Therefore MyClass::m_object which is defined first, is also initialized first, and destroyed last.
Do things change if the line ... moves to another .cpp file and its file name causes the order to change?
Yes, things change. Order of definition across translation units is unspecified, so there is no guarantee about the relative initialization order (and thus no guarantee about the relative destruction order).
The typical solution to dependencies between static objects is to use the initialization on first use idiom, which is simply replacing the use of a global static with a function that returns a reference to a local static:
class MyClass
{
static SomeObject& m_object() {
static SomeObject s;
return s;
}
};
Local static objects are initialized when execution first reaches the point of declaration; hence the name of the idiom.
Any object whose own initialization calls MyClass::m_object(), is guaranteed to be destroyed before the local static s is destroyed and therefore can rely on its existence for their entire lifetime - including the destructor and regardless of translation unit bounds.
Check this out if you're using visual studio - windows: otherwise you may have to use something similar such as __PRETTY_FUNCITON__, etc.
class SomeObject {
public:
SomeObject() {
std::cout << __FUNCTION__ << " was called: SomeObject created." << std::endl;
}
~SomeObject() {
std::cout << __FUNCTION__ << " was called: SomeObject destroyed." << std::endl;
}
};
class MyClass {
public:
static SomeObject m_object;
MyClass() {
std::cout << __FUNCTION__ << " was called: MyClass created." << std::endl;
}
~MyClass() {
std::cout << __FUNCTION__ << " was called: MyClass destroyed." << std::endl;
}
static bool setupStaticMember() {
std::cout << __FUNCTION__ << " was called... " << std::endl;
return true;
}
};
SomeObject MyClass::m_object;
bool dummy = MyClass::setupStaticMember();
MyClass gMyClass;
int main() {
_getch();
return 0;
}
Output in debugger console while waiting for key press:
SomeObject::SomeObject was called: SomeObject created.
MyClass::setupStaticMember was called...
MyClass::MyClass was called: MyClass created.
Then as key press is entered and console from debugger closes (visual studio 2017)...
MyClass::~MyClass was called: MyClass destroyed.
SomeObject::~SomeObject was called: SomeObject destroyed.
To test this out fully just go to the *.exe's path in the console directly and call the executable. You will see the same lines above while the application is running but after you press a key and enter to finish the application the last 2 lines are then called in that order.
These are all in the main.cpp file (same translation unit).
This does show the order that objects are created. Now if you are in a class hierarchy then you need to make sure you are virtualizing your classes for proper construction - destruction order.
Static member of a class is a class level variable and under the class scope. As a static member is under the scope of class only it is accessible from all the object instantiated from that class with :: (classname::static_variable) operator. As it is not a object variable you can not release from destructor of the class.
Suppose you have created ten objects from that class in various location in your codes and one object is going out of its scope and will call its destructor and if you release the static variable from that destructor what would happened in other objects? As they are all sharing the same static member. That is the reason a static member never initialized in a constructor.
Hence a static member will be release from the memory only when program exit.

Destruction of local Static variable

I have a function f() with two local static variables, one of them (t3) points to dynamically allocated memory and other is normal one t1 (which I think is allocated on stack.).
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const char *name): _name(name)
{
cout << _name << " created" << endl;
}
~test()
{
cout << _name << " destroyed" << endl;
}
string _name;
static test tc; // static member
};
test test::tc(".class static data member");
test gvar("..global non-static object ");
static test sgvar("...global static object");
void f()
{
static int num = 10 ; // POD type, init before enter main function
static test tl("..Local static object on (stack???)");
static test* t3 = new test("..Local static object in free store");
test t2("...local non-static object.....");
cout << "Function executed" << endl;
}
int main()
{
cout << "----------------------Program start----------------------" << endl;
test t("LocalToMain non-static object");
f();
cout << "----------------------Program end-------------------------" << endl;
return 0;
}
I get the following output
# main
.class static data member created
..global non-static object created
...global static object created
----------------------Program start----------------------
LocalToMain non-static object created
..Local static object on stack created
..Local static object in free store created
...local non-static object..... created
Function executed
...local non-static object..... destroyed
----------------------Program end-------------------------
LocalToMain non-static object destroyed
..Local static object on stack destroyed
...global static object destroyed
..global non-static object destroyed
.class static data member destroyed
My Question is
Destructor of local static t1 is called, but destructor for local static t3 is not called.Why?
What is the storage duration of t3 and t1?
Is t1 stored on stack and t2 on heap ? if not where are they stored?
First of all, the C++ specification doesn't actually say anything about where local (static or non-static) variables are stored, it's up to the compiler.
As for your questions, the variable t3 is destructed, but it's the pointer that is destructed and not what it points to. As you don't delete the object you new it will not be destructed by the run-time, and the memory will "leak".
The life-time of both t1 and t3 is the life-time of the program.
And where t1 is stored I don't know, probably in a special data segment loaded into memory, but t2 is a normal local variable which most compilers store on the stack.
There's really not much difference between e.g. num and t1. A local static variable is like any other local static variable, no matter the type.