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.
Related
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::~
I am working on a class ex1 which needs one static member variable y. That static member variable is a pointer to an object of class ex2 which has its own constructor and destructor. Now I know how to initialize the variable y by defining it outside the class. But how to call the destructor for variable y? I need to use delete statement, but where to place that statement. I need to call both constructor and destructor of class ex2.
An equivalent code of my problem is shown below with the output:
#include<iostream>
class ex2 {
public:
int n;
ex2(int num) {
n = num;
std::cout << "Constructor of ex2\n";
}
~ex2(){std::cout << "Destructor of ex2\n";}
};
class ex1 {
public:
static ex2 *y; //static member variable
ex1() {std::cout << "Constructor of ex1\n";}
~ex1() {std::cout << "Destructor of ex1\n";}
};
ex2 *ex1::y = new ex2(90); //definition for static member
int main()
{
ex1 y1;
return 0;
}
The output for this is:
Constructor of ex2
Constructor of ex1
Destructor of ex1
Please help on how to call the destructor of ex2. Also the destructor need to be called after all instances of class ex1 are destroyed.
You could create regular class that on destructions calls delete on your pointer:
struct Destroyer {
ex2 *p;
~Destroyer() { delete p; }
};
ex2 *ex1::y = new ex2(90);
Destroyer dex2{ex1::y};
PS: In my experience you should avoid putting too much logic during automatic initialization and automatic destruction. There are things to pay high attention to (what parts of your system are still usable when doing the destruction? what parts are already usable during construction?) and moreover I discovered even tools like debuggers don't work well during those times. As a rule for example you should never ever do anything that can fail for whatever reason before main is started or after main is completed because that will be a pain to manage (how can you log an error during initialization if the error logging subsystem wasn't initialized yet? how can you log the error during shutdown if the logging system was already shut down?).
I also think the C++ standard specification is kind of fuzzy about those issues so you may get surprises depending on compilers and over the years I preferred moving away from lazy/automatic initialization and destruction to explicit initialization and destruction done in main in the sequence I want and that I know to be correct.
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
In C++ if we define a class destructor as:
~Foo(){
return;
}
upon calling this destructor will the object of Foo be destroyed or does
explicitly returning from the destructor mean that we don't ever want to destroy it.
I want to make it so that a certain object is destroyed only through another objects destructor i.e. only when the other object is ready to be destroyed.
Example:
class Class1{
...
Class2* myClass2;
...
};
Class1::~Class1(){
myClass2->status = FINISHED;
delete myClass2;
}
Class2::~Class2(){
if (status != FINISHED) return;
}
I searched online and couldn't seem to find an answer to my question.
I've also tried figuring it out myself by going through some code step by step with a debugger but can't get a conclusive result.
No, you can't prevent the object from being destroyed by return statement, it just means the execution of the dtor's body will end at that point. After that it still will be destroyed (including its members and bases), and the memory still will be deallocated.
You migth throw exception.
Class2::~Class2() noexcept(false) {
if (status != FINISHED) throw some_exception();
}
Class1::~Class1() {
myClass2->status = FINISHED;
try {
delete myClass2;
} catch (some_exception& e) {
// what should we do now?
}
}
Note it's a terrible idea indeed. You'd better to reconsider the design, I'm sure there must be a better one. Throwing exception won't stop the destruction of its bases and members, just make it possible to get the process result of Class2's dtor. And what could be done with it is still not clear.
~Foo(){
return;
}
means exactly the same as:
~Foo() {}
It is similar to a void function; reaching the end without a return; statement is the same as having return; at the end.
The destructor contains actions that are performed when the process of destroying a Foo has already begun. It's not possible to abort a destruction process without aborting the entire program.
[D]oes explicitly returning from the destructor mean that we don't ever want to destroy it?
No. An early return (via return; or throw ...) only means the rest of the body of the destructor is not executed. The base and members are still destroyed and their destructors still run, see [except.ctor]/3.
For an object of class type of any storage duration whose initialization or destruction is terminated by an exception, the destructor is invoked for each of the object's fully constructed subobjects...
See below for code samples of this behaviour.
I want to make it so that a certain object is destroyed only through another objects destructor i.e. only when the other object is ready to be destroyed.
It sounds like the question is rooted in the issue of ownership. Deleting the "owned" object only once the parent is destroyed in a very common idiom and achieved with one of (but not limited to);
Composition, it is an automatic member variable (i.e. "stack based")
A std::unique_ptr<> to express exclusive ownership of the dynamic object
A std::shared_ptr<> to express shared ownership of a dynamic object
Given the code example in the OP, the std::unique_ptr<> may be a suitable alternative;
class Class1 {
// ...
std::unique_ptr<Class2> myClass2;
// ...
};
Class1::~Class1() {
myClass2->status = FINISHED;
// do not delete, the deleter will run automatically
// delete myClass2;
}
Class2::~Class2() {
//if (status != FINISHED)
// return;
// We are finished, we are being deleted.
}
I note the if condition check in the example code. It hints at the state being tied to the ownership and lifetime. They are not all the same thing; sure, you can tie the object reaching a certain state to it's "logical" lifetime (i.e. run some cleanup code), but I would avoid the direct link to the ownership of the object. It may be a better idea to reconsider some of the semantics involved here, or allow the "natural" construction and destruction to dictate the object begin and end states.
Side note; if you have to check for some state in the destructor (or assert some end condition), one alternative to the throw is to call std::terminate (with some logging) if that condition is not met. This approach is similar to the standard behavior and result when an exception is thrown when unwinding the stack as a result of an already thrown exception. This is also the standard behavior when a std::thread exits with an unhandled exception.
[D]oes explicitly returning from the destructor mean that we don't ever want to destroy it?
No (see above). The following code demonstrates this behaviour; linked here and a dynamic version. The noexcept(false) is needed to avoid std::terminate() being called.
#include <iostream>
using namespace std;
struct NoisyBase {
NoisyBase() { cout << __func__ << endl; }
~NoisyBase() { cout << __func__ << endl; }
NoisyBase(NoisyBase const&) { cout << __func__ << endl; }
NoisyBase& operator=(NoisyBase const&) { cout << __func__ << endl; return *this; }
};
struct NoisyMember {
NoisyMember() { cout << __func__ << endl; }
~NoisyMember() { cout << __func__ << endl; }
NoisyMember(NoisyMember const&) { cout << __func__ << endl; }
NoisyMember& operator=(NoisyMember const&) { cout << __func__ << endl; return *this; }
};
struct Thrower : NoisyBase {
Thrower() { cout << __func__ << std::endl; }
~Thrower () noexcept(false) {
cout << "before throw" << endl;
throw 42;
cout << "after throw" << endl;
}
NoisyMember m_;
};
struct Returner : NoisyBase {
Returner() { cout << __func__ << std::endl; }
~Returner () noexcept(false) {
cout << "before return" << endl;
return;
cout << "after return" << endl;
}
NoisyMember m_;
};
int main()
{
try {
Thrower t;
}
catch (int& e) {
cout << "catch... " << e << endl;
}
{
Returner r;
}
}
Has the following output;
NoisyBase
NoisyMember
Thrower
before throw
~NoisyMember
~NoisyBase
catch... 42
NoisyBase
NoisyMember
Returner
before return
~NoisyMember
~NoisyBase
According to the C++ Standard (12.4 Destructors)
8 After executing the body of the destructor and destroying any
automatic objects allocated within the body, a destructor for class X
calls the destructors for X’s direct non-variant non-static data
members, the destructors for X’s direct base classes and, if X is the
type of the most derived class (12.6.2), its destructor calls the
destructors for X’s virtual base classes. All destructors are called
as if they were referenced with a qualified name, that is, ignoring
any possible virtual overriding destructors in more derived classes.
Bases and members are destroyed in the reverse order of the completion
of their constructor (see 12.6.2). A return statement (6.6.3) in a
destructor might not directly return to the caller; before
transferring control to the caller, the destructors for the members
and bases are called. Destructors for elements of an array are called
in reverse order of their construction (see 12.6).
So a returning statement does not prevent the object for which the destructor is called to be destroyed.
does explicitly returning from the destructor mean that we don't ever want to destroy it.
No.
The destructor is a function so you can use the return keyword inside of it but that won't prevent the destruction of the object, once you are inside the destructor you are already destroying your object so any logic that wants to prevent that will have to occur before.
For some reason i intuitively think your design problem can be solved with a shared_ptr and maybe a custom deleter, but that would require more info on the said problem.
All stack-based objects inside will get destructed, no matter how soon you return from the destructor. If you miss to delete dynamically allocated objects, then there would be intentional memory leak.
This is the whole idea how move-constructors would work. The move CTOR would simply take original object's memory. The destructor of original object simply wont/cant call delete.
No. return just means exit the method, it doesn't stop the destruction of the object.
Also, why would you want to? If the object is allocated on the stack and you somehow managed to stop destruction then the object would live on a reclaimed part of the stack that will probably be overwritten by the next function call, which may write all over your objects memory and create undefined behavior.
Likewise, if the object is allocated on the heap and you managed to prevent destruction you'd have a memory leak as the code calling delete would assume that it didn't need to hold on to a pointer to the object whilst it's actually still there and taking up memory that nobody is referencing.
Of course not. Explicit call of 'return' ist 100% equivalent to implicit returning after execution of the destructor.
You can make a new method to make the object "commit suicide" and keep the destructor empty, so something like this will do the job you would like to do:
Class1::~Class1()
{
myClass2->status = FINISHED;
myClass2->DeleteMe();
}
void Class2::DeleteMe()
{
if (status == FINISHED)
{
delete this;
}
}
Class2::~Class2()
{
}
So, as all the others pointed out, return is not a solution.
The first thing I would add is that you shouldn't usually worry about this. Unless your professor explicitly asked.
It would be very odd if you could't trust the external class to only delete your class at the right time, and I figure no one else is seeing it.
If the pointer is passed around, the pointer would very probably be shared_ptr/weak_ptr, and let it destroy your class at the right moment.
But, hey, it's good to wonder how we would solve an odd problem if it ever arose, if we learn something (and don't waste time while on a deadline!)
So what for a solution? If you can at least trust the destructor of Class1 not to destroy your object too early, then you can just declare the destructor of Class2 as private, and then declare the destructor of Class1 as friend of Class2, like this:
class Class2;
class Class1 {
Class2* myClass2;
public:
~Class1();
};
class Class2 {
private:
~Class2();
friend Class1::~Class1();
};
Class1::~Class1() {
delete myClass2;
}
Class2::~Class2() {
}
As a bonus, you don't need the 'status' flag; which is good -if someone wanted this bad to screw with you, why wouldn't set the status flag to FINISHED anywhere else, and then call delete?
This way, you have actual guarantee that the object can be destroyed nowhere else than in the destructor of Class1.
Of course, the destructor of Class1 gets access to all private members of Class2. It might not matter -after all, Class2 is about to be destroyed anyway! But if it does, we can conjure even more convoluted ways to work around it; why not. For instance:
class Class2;
class Class1 {
private:
int status;
Class2* myClass2;
public:
~Class1();
};
class Class2Hidden {
private:
//Class2 private members
protected:
~Class2Hidden();
public:
//Class2 public members
};
class Class2 : public Class2Hidden {
protected:
~Class2();
friend Class1::~Class1();
};
Class1::~Class1() {
delete myClass2;
}
Class2Hidden::~Class2Hidden() {
}
Class2::~Class2() {
}
This way the public members will still be available in the derived class, but the private members will actually be private. ~Class1 will only get access to the private and protected members of Class2, and the protected members of Class2Hidden; which in this case is only the destructors.
If you need to keep a protected member of Class2 protected from the destructor of Class1... there are ways, but it really depends on what you are doing.
Good luck!
For this case you could use a class-specific overload of the delete operator.
So for you Class2 you could something like this
class Class2
{
static void operator delete(void* ptr, std::size_t sz)
{
std::cout << "custom delete for size " << sz << '\n';
if(finished)
::operator delete(ptr);
}
bool Finished;
}
Then if you set the finished to true before the delete, the actual deletion will be called.
Note that i haven't tested it, i just modified the code that i've found here
http://en.cppreference.com/w/cpp/memory/new/operator_delete
Class1::~Class1()
{
class2->Finished = true;
delete class2;
}
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;
}