By static and global objects, I presume you mean objects with static lifetime defined at namespace scope. When such objects are defined with local scope, the rules are slightly different.
Formally, C++ initializes such variables in three phases: 1. Zero initialization 2. Static initialization 3. Dynamic initialization The language also distinguishes between variables which require dynamic initialization, and those which require static initialization: all static objects (objects with static lifetime) are first zero initialized, then objects with static initialization are initialized, and then dynamic initialization occurs.
As a simple first approximation, dynamic initialization means that some code must be executed; typically, static initialization doesn't. Thus:
extern int f();
int g1 = 42; // static initialization
int g2 = f(); // dynamic initialization
Another approximization would be that static initialization is what C supports (for variables with static lifetime), dynamic everything else.
How the compiler does this depends, of course, on the initialization, but on disk based systems, where the executable is loaded into memory from disk, the values for static initialization are part of the image on disk, and loaded directly by the system from the disk. On a classical Unix system, global variables would be divided into three "segments":
text: The code, loaded into a write protected area. Static variables with `const` types would also be placed here. data: Static variables with static initializers. bss: Static variables with no-initializer (C and C++) or with dynamic initialization (C++). The executable contains no image for this segment, and the system simply sets it all to `0` before starting your code.I suspect that a lot of modern systems still use something similar.
EDIT:
One additional remark: the above refers to C++03. For existing
programs, C++11 probably doesn't change anything, but it does
add constexpr (which means that some user defined functions
can still be static initialization) and thread local variables,
which opens up a whole new can of worms.
By static and global objects, I presume you mean objects with static lifetime defined at namespace scope. When such objects are defined with local scope, the rules are slightly different.
Formally, C++ initializes such variables in three phases: 1. Zero initialization 2. Static initialization 3. Dynamic initialization The language also distinguishes between variables which require dynamic initialization, and those which require static initialization: all static objects (objects with static lifetime) are first zero initialized, then objects with static initialization are initialized, and then dynamic initialization occurs.
As a simple first approximation, dynamic initialization means that some code must be executed; typically, static initialization doesn't. Thus:
extern int f();
int g1 = 42; // static initialization
int g2 = f(); // dynamic initialization
Another approximization would be that static initialization is what C supports (for variables with static lifetime), dynamic everything else.
How the compiler does this depends, of course, on the initialization, but on disk based systems, where the executable is loaded into memory from disk, the values for static initialization are part of the image on disk, and loaded directly by the system from the disk. On a classical Unix system, global variables would be divided into three "segments":
text: The code, loaded into a write protected area. Static variables with `const` types would also be placed here. data: Static variables with static initializers. bss: Static variables with no-initializer (C and C++) or with dynamic initialization (C++). The executable contains no image for this segment, and the system simply sets it all to `0` before starting your code.I suspect that a lot of modern systems still use something similar.
EDIT:
One additional remark: the above refers to C++03. For existing
programs, C++11 probably doesn't change anything, but it does
add constexpr (which means that some user defined functions
can still be static initialization) and thread local variables,
which opens up a whole new can of worms.
Preface: The word "static" has a vast number of different meanings in C++. Don't get confused.
All your objects have static storage duration. That is because they are neither automatic nor dynamic. (Nor thread-local, though thread-local is a bit like static.)
In C++, Static objects are initialized in two phases: static initialization, and dynamic initialization.
Dynamic initialization requires actual code to execute, so this happens for objects that start with a constructor call, or where the initializer is an expression that can only be evaluated at runtime.
Static initialization is when the initializer is known statically and no constructor needs to run. (Static initialization is either zero-initialization or constant-initialization.) This is the case for your
intvariables with constant initializer, and you are guaranteed that those are indeed initialized in the static phase.(Static-storage variables with dynamic initialization are also zero-initialzed statically before anything else happens.)
The crucial point is that the static initialization phase doens't "run" at all. The data is there right from the start. That means that there is no "ordering" or any other such dynamic property that concerns static initialization. The initial values are hard-coded into your program binary, if you will.
c - Why are global variables always initialized to '0', but not local variables? - Stack Overflow
c++ - Initializing global variable class - Stack Overflow
oop - C++ global object initialization fails -- why? and is it possible to put objects in .DATA section? - Stack Overflow
c++ - Initialize before any global objects - Stack Overflow
Yes, all members of a are guaranteed to be initialised to 0.
From section 3.5.7 of the C89 standard
If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
"Global variables" are defined at file scope, outside any function. All variables that are defined at file scope and all variables that are declared with the keyword static have something called static storage duration. This means that they will be allocated in a separate part of the memory and exist throughout the whole lifetime of the program.
It also means that they are guaranteed to be initialized to zero on any C compiler.
From the current C standard C11 6.7.9/10:
"... If an object that has static or thread storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;"
Practically, this means that if you initialize your global variable to a given value, it will have that value and it will be allocated in a memory segment usually referred to as .data. If you don't give it a value, it will be allocated in another segment called .bss. Globals will never be allocated on the stack.
Because that's the way it is, according to the C Standard. The reason for that is efficiency:
static variables are initialized at compile-time, since their address is known and fixed. Initializing them to
0does not incur a runtime cost.automatic variables can have different addresses for different calls and would have to be initialized at runtime each time the function is called, incurring a runtime cost that may not be needed. If you do need that initialization, then request it.
global and static variables are stored in the Data Segment (DS) when initialized and block start by symbol (BSS)` when uninitialized.
These variables have a fixed memory location, and memory is allocated at compile time.
Thus global and static variables have '0' as their default values.
Whereas auto variables are stored on the stack, and they do not have a fixed memory location.
Memory is allocated to auto variables at runtime, but not at
compile time. Hence auto variables have their default value as garbage.
1. Straightforward answer
If the class is assignable/copy constructible you can just write
QFile file; //QFile class
int main()
{
file = QFile("C:\\example");
}
2. Use indirection
If not, you'll have to resort to other options:
QFile* file = 0;
int main()
{
file = new QFile("C:\\example");
//
delete file;
}
Or use boost::optional<QFile>, std::shared_ptr<QFile>, boost::scoped_ptr<QFile> etc.
3. Use singleton-related patterns:
Due to the Static Initialization Fiasco you could want to write such a function:
static QFile& getFile()
{
static QFile s_file("C:\\example"); // initialized once due to being static
return s_file;
}
C++11 made such a function-local static initialization thread safe as well (quoting the C++0x draft n3242, §6.7:)

The same way:
// file.cpp
QFile file("C:\\example");
int main()
{
// use `file`
}
The constructors of all global objects execute before main() is invoked (and inversely for destructors).
Using a plain struct or class is, indeed, possible:
class Test { // or use struct without explicit public accessibility
public:
int val;
};
Test test1 = { 5 };
You:
- cannot do any fancy construction work using this plain layout and
- cannot have any member requiring construction.
Otherwise, you do not need worry about new or malloc if you program as you did in your example: test2 is cheaply allocated on the stack even though a constructor is called.
Just as a side note: consider using initializer lists when you do use constructors:
class Test {
int m_val;
public:
Test(int val) : m_val(val) {}
};
In embedded systems programming, it is very bad practice to rely on constructor calls for objects with static storage duration.
This is because many compilers have the option to create a non-standard "minimal startup", meaning that the compiler will ignore the requirements of the C and C++ standards and skip all initialization of static storage duration variables, including calling constructors for such objects.
Also, in general C++ you have to be careful not to rely on order of initialization of static storage duration variables. If you have object A and B, and object A is initialized first, there must not be any code in A's constructor that relies on B to be initialized. More info in the C++ FAQ.
Say in a function there is a static local variable. How does the function know to only set the value the first time the function is called? Is the local static variable actually stored and initialized identical other global variables and the compiler just hides the variable from other functions?
void function() {
static int x = 20;
x++;
printf("The static variable is: %d", x);
}My second question is in which order are global and static variables initialized? Some variables might be initialized based on another variable or as a return value of a function which may depend on other global variables. Are there limitations on how global or static variables can be initialized? Is there a requirement that the initial value of all global and static variables must be able to be determined at compile time? Does the compiler execute any functions that initialize global or static variables at compile time and throw an error if it contains anything that cannot be evaluated at compile time?
int a, b, c, d; // global variables
d = time(NULL) // unknown result at compile
c = a+5;
b = initializeB(); //function may internally use other global variables or other function calls that are unable to be evaluated at compile time
a = 10;
void function() {
static int x = initializeX(); //function may internally use other global variables or other function calls that are unable to be evaluated at compile time
x++;
printf("The static variable is: %d", x);
}Main problem with global variables in C++ that compilers don't guarantee initialization order. Let's you have 2 global variables with constructors:
global_A g_a;
...
global_B g_b;
...
global_A::global_A()
{
this->test = 5; // test is int
}
...
global_B::global_B()
{
printf( "%d", g_a.test );
}
If initialization order of g_a and g_b is undefined, then sometimes you can get situation when constructor of g_b would be called before g_a and variable g_a.test would be undefined. The worst thing - sometimes it works well.
Note, if global variables in same source file then you may be sure that order will be same as global variables are defined. But using global variables with dependencies is bad practice because other people who will work with this code may not know about dependency between global variables and got troubles if move one of global variable to other file.
Global's initialization happens before main() gets called and the UI setup stuff happens if that takes too long then the game window may take a long time to show up.
Common rule in UX (user experience) is to react to user input as fast as possible even if the result is not yet available.
This is a common setup for games as they will show a semi-static screen for some time as they load all the needed assets before showing the main menu.
I see two problems with this, one a legality problem and one a usability problem.
The first problem is alignment: MyObject::s_pMyPlaceholder is not guaranteed to be suitably aligned to hold a MyObject.
The second problem is that you have restricted yourself to a single object of type MyObject. Create a second and you have overwritten the first with no warning.
I would suggest using boost::optional to delay initialisation of objects.
I don't think you have a formal guarantee that your solution works on every compliant implementation, because the C++ standard doesn't guarantee that statically allocated arrays of char are aligned as would be required by any object of the same size.