parts/4.5.Initialization.md

4.5 Initialization

C++ provides a number of ways that an object can be initialized - 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]; - Zero initialization - Default initialization copy, move, default constructor

C++ has many forms of initilization, which generally guarantee that subsequent access to the declared object will be well-defined, however C++ does not always guarantee that it contains a legal value unless the programmer explicitly initializes it with a value. See ##6.22 Missing initialization of variables [LAV]#LAV.

The kind of initialization that happens in C++ when an explicit initializer is not used depends on the context of the declaration.

   int i; // zero-initialized in global name space, 
    void foo()
   {
       int i; // default initialized, inderterminate value
       int j{};  // value-initialized to zero
    }
 

Non-local variables with static storage duration that are dynamically initialized can cause undefined behavior if the initialization depends on other such variables, see ##6.22 Missing initialization of variables [LAV]#LAV.

The lifetime of most objects of a class type begins when the object’s constructor has completed. In some situations binding a reference to a temporary will extend the lifetime of the temporary. See ##4.4 Lifetime and ## 6.33 Dangling References to Stack Frames [DCM]. // In any case, an object should not be accessed until its initialization is complete (including concurrency???). Richard C thinks that https://eel.is/c++draft/basic.start.dynamic#5 means that there is no danger of one thread accessing a dynamically initialized global variable before the initialization has taken place - is that the case?

When a function is called, each parameter is initialized with its corresponding argument. The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter, see ## 6.24 Side-effects and Order of Evaluation of Operands [SAM]. On the other hand, the value computation and side effects of the initializer-clauses in an initializer-list are evaluated in the order they appear.

There are many ways for a user to construct, or initialize, an object.