Initialization
Initialization of a variable provides its initial value at the time of construction.
The initial value may be provided in the initializer section of a declarator or a new expression. It also takes place during function calls: function parameters and the function return values are also initialized.
For each declarator, the initializer may be one of the following:
( expression-list )
|
(1) | ||||||||
= expression
|
(2) | ||||||||
{ initializer-list }
|
(3) | ||||||||
Depending on context, initializer may invoke one of the following:
- Value initialization, e.g. std::string s{};
- Direct initialization, e.g. std::string s("hello");
- Copy initialization, e.g. std::string s = "hello";
- List initialization, e.g. std::string s{'a', 'b', 'c'};
- Aggregate initialization, e.g. char a[3] = {'a', 'b'};
- Reference initialization, e.g. char& c = a[0];
If no initializer is provided, the rules of default initialization apply.
[edit] Non-local variables
All variables with static storage duration are initialized as part of program startup, before the execution of the main function begins. All variables with thread-local storage duration are initialized as part of thread launch, before the execution of the thread function begins. For both of these classes of variables, initialization occurs in stages:
.bss
segment, which is zeroed out by the OS when loading the program)The compilers are allowed to initialize dynamically-initialized variables as part of static initialization (essentially, at compile time), if both of these are true:
This section is incomplete Reason: when ambiguous, examples |
[edit] Class members
Non-static data members can be initialized with member initializer list or with a in-class brace-or-equal initializer.