Example Static and Dynamic Initialization

后端 未结 1 1339
别跟我提以往
别跟我提以往 2020-12-21 13:29

Is there an example in which variable is initialized both in static and dynamic way. I.e. as said the spec.

Static initialization shall be performed b

相关标签:
1条回答
  • 2020-12-21 13:45

    Sure: static initialization, which fills all objects with zero, takes place before any user code runs.

    Those zeros might be visible during the execution of other initializers. Read about the "Static Initialization Order Fiasco"

    Note that objects are not deemed constructed until after dynamic initialization completes, and you have to follow the lifetime rules. [basic.life] in the Standard says:

    The lifetime of an object is a runtime property of the object. An object is said to have non-trivial initialization if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial default constructor. [ Note: initialization by a trivial copy/move constructor is non-trivial initialization. — end note ] The lifetime of an object of type T begins when:

    • storage with the proper alignment and size for type T is obtained, and
    • if the object has non-trivial initialization, its initialization is complete.

    and

    The properties ascribed to objects throughout this International Standard apply for a given object only during its lifetime. [ Note: In particular, before the lifetime of an object starts and after its lifetime ends there are significant restrictions on the use of the object, as described below, in 12.6.2 and in 12.7. Also, the behavior of an object under construction and destruction might not be the same as the behavior of an object whose lifetime has started and not ended. 12.6.2 and 12.7 describe the behavior of objects during the construction and destruction phases. — end note ]

    and

    Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see 12.7. Otherwise, such a glvalue refers to allocated storage (3.7.4.2), and using the properties of the glvalue that do not depend on its value is well-defined. The program has undefined behavior if:

    • an lvalue-to-rvalue conversion (4.1) is applied to such a glvalue,
    • the glvalue is used to access a non-static data member or call a non-static member function of the object, or
    • the glvalue is bound to a reference to a virtual base class (8.5.3), or
    • the glvalue is used as the operand of a dynamic_cast (5.2.7) or as the operand of typeid.

    So, accessing the (zeroed) content of objects of non-primitive type can easily lead to undefined behavior.

    0 讨论(0)
提交回复
热议问题