Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      Initialization

      From cppreference.com
      <cpp‎ |language
       
       
      C++ language
      General topics
      Flow control
      Conditional execution statements
      Iteration statements (loops)
      Jump statements
      Functions
      Function declaration
      Lambda function expression
      inline specifier
      Dynamic exception specifications(until C++17*)
      noexcept specifier(C++11)
      Exceptions
      Namespaces
      Types
      Specifiers
      constexpr(C++11)
      consteval(C++20)
      constinit(C++20)
      Storage duration specifiers
      Initialization
      Expressions
      Alternative representations
      Literals
      Boolean -Integer -Floating-point
      Character -String -nullptr(C++11)
      User-defined(C++11)
      Utilities
      Attributes(C++11)
      Types
      typedef declaration
      Type alias declaration(C++11)
      Casts
      Memory allocation
      Classes
      Class-specific function properties
      Special member functions
      Templates
      Miscellaneous
       
       

      Initialization of a variable provides its initial value at the time of construction.

      The initial value may be provided in the initializer section of adeclarator or anew expression. It also takes place during function calls: function parameters and the function return values are also initialized.

      Contents

      [edit]Initializers

      For each declarator, theinitializer (if exists) may be one of the following:

      =expression (1)
      = {}
      = {initializer-list}
      = {designated-initializer-list}
      (2)

      (since C++20)
      (expression-list)
      (initializer-list)
      (3)(until C++11)
      (since C++11)
      {}
      {initializer-list}
      {designated-initializer-list}
      (4)(since C++11)
      (since C++11)
      (since C++20)
      1) Copy-initialization syntax.
      2)Aggregate initialization syntax.(until C++11)List-initialization syntax.(since C++11)
      3) Direct-initialization syntax.
      4) List-initialization syntax.
      expression - any expression (except unparenthesizedcomma expressions)
      expression-list - a comma-separated list of expressions (except unparenthesized comma expressions)
      initializer-list - a comma-separated list of initializer clauses (see below)
      designated-initializer-list - a comma-separated list ofdesignated initializer clauses


      Aninitializer clause may be one of the following:

      expression (1)
      {} (2)
      {initializer-list} (3)
      {designated-initializer-list} (4)(since C++20)

      Syntaxes(2-4) are collectively calledbrace-enclosed initializer list.

      [edit]Initializer semantics

      If no initializer is specified for an object, the object isdefault-initialized. If no initializer is specified for areference, the program is ill-formed.

      If the initializer specified for an object is() (cannot appear in declarators due to the syntax restriction), the object isvalue-initialized. If the initializer specified for a reference is(), the program is ill-formed.

      The semantics of initializers are as follows:

      • If the entity being initialized is a reference, seereference initialization.
      • Otherwise, the entity being initialized is an object. Given the type of the object asT:
      • If the initializer is of syntax(2):
      (until C++11)
      (since C++11)
      #include <string> std::string s1;// default-initializationstd::string s2();// NOT an initialization!// actually declares a function “s2”// with no parameter and returns std::stringstd::string s3="hello";// copy-initializationstd::string s4("hello");// direct-initializationstd::string s5{'a'};// list-initialization (since C++11) char a[3]={'a','b'};// aggregate initialization// (part of list initialization since C++11)char& c= a[0];// reference initialization

      [edit]Non-local variables

      All non-local variables with staticstorage duration are initialized as part of program startup, before the execution of themain function begins (unless deferred, see below). All non-local variables with thread-local storage duration are initialized as part of thread launch, sequenced-before the execution of the thread function begins. For both of these classes of variables, initialization occurs in two distinct stages:

      [edit]Static initialization

      There are two forms of static initialization:

      1) If possible,constant initialization is applied.
      2) Otherwise, non-local static and thread-local variables arezero-initialized.

      In practice:

      • Constant initialization is usually applied at compile time. Pre-calculated object representations are stored as part of the program image. If the compiler doesn't do that, it must still guarantee that the initialization happens before any dynamic initialization.
      • Variables to be zero-initialized are placed in the.bss segment of the program image, which occupies no space on disk and is zeroed out by the OS when loading the program.

      [edit]Dynamic initialization

      After all static initialization is completed, dynamic initialization of non-local variables occurs in the following situations:

      1)Unordered dynamic initialization, which applies only to (static/thread-local) class templatestatic data membersandvariable templates(since C++14) that aren'texplicitly specialized. Initialization of such static variables is indeterminately sequenced with respect to all other dynamic initializationexcept if the program starts a thread before a variable is initialized, in which case its initialization is unsequenced(since C++17). Initialization of such thread-local variables is unsequenced with respect to all other dynamic initialization.
      2)Partially-ordered dynamic initialization, which applies to all inline variables that are not an implicitly or explicitly instantiated specialization. If a partially-ordered V is defined before ordered or partially-ordered W in every translation unit, the initialization of V is sequenced before the initialization of W (or happens-before, if the program starts a thread).
      (since C++17)
      3)Ordered dynamic initialization, which applies to all other non-local variables: within a single translation unit, initialization of these variables is alwayssequenced in exact order their definitions appear in the source code. Initialization of static variables in different translation units is indeterminately sequenced. Initialization of thread-local variables in different translation units is unsequenced.

      If the initialization of a non-local variable with static or thread storage duration exits via an exception,std::terminate is called.

      [edit]Early dynamic initialization

      The compilers are allowed to initialize dynamically-initialized variables as part of static initialization (essentially, at compile time), if the following conditions are both true:

      1) the dynamic version of the initialization does not change the value of any other object of namespace scope prior to its initialization
      2) the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically.

      Because of the rule above, if initialization of some objecto1 refers to a namespace-scope objecto2, which potentially requires dynamic initialization, but is defined later in the same translation unit, it is unspecified whether the value ofo2 used will be the value of the fully initializedo2 (because the compiler promoted initialization ofo2 to compile time) or will be the value ofo2 merely zero-initialized.

      inlinedouble fd(){return1.0;} externdouble d1; double d2= d1;// unspecified:// dynamically initialized to 0.0 if d1 is dynamically initialized, or// dynamically initialized to 1.0 if d1 is statically initialized, or// statically initialized to 0.0 (because that would be its value// if both variables were dynamically initialized) double d1= fd();// may be initialized statically or dynamically to 1.0

      [edit]Deferred dynamic initialization

      It is implementation-defined whether dynamic initialization happens-before the first statement of the main function (for statics) or the initial function of the thread (for thread-locals), or deferred to happen after.

      If the initializationof a non-inline variable(since C++17) is deferred to happen after the first statement of main/thread function, it happens before the firstODR-use of any variable with static/thread storage duration defined in the same translation unit as the variable to be initialized. If no variable or function is ODR-used from a given translation unit, the non-local variables defined in that translation unit may never be initialized (this models the behavior of an on-demand dynamic library). However, as long as anything from a translation unit is ODR-used, all non-local variables whose initialization or destruction has side effects will be initialized even if they are not used in the program.

      If the initialization of an inline variable is deferred, it happens before the firstODR-use of that specific variable.

      (since C++17)
      // ============// == File 1 == #include "a.h"#include "b.h" B b;A::A(){ b.Use();} // ============// == File 2 == #include "a.h" A a; // ============// == File 3 == #include "a.h"#include "b.h" extern A a;extern B b; int main(){    a.Use();    b.Use();} // If a is initialized before main is entered, b may still be uninitialized// at the point where A::A() uses it (because dynamic initialization is// indeterminately sequenced across translation units) // If a is initialized at some point after the first statement of main (which odr-uses// a function defined in File 1, forcing its dynamic initialization to run),// then b will be initialized prior to its use in A::A

      [edit]Static local variables

      For initialization of local (that is, block scope) static and thread-local variables, seestatic block variables.

      Initializer is not allowed in a block-scope declaration of a variable withexternal or internal linkage. Such a declaration must appear withextern and cannot be a definition.

      [edit]Class members

      Non-static data members can be initialized withmember initializer list or with adefault member initializer.

      [edit]Notes

      The order of destruction of non-local variables is described instd::exit.

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      CWG 270C++98the order of initializing static data members
      of class templates was unspecified
      specified as unordered except for
      explicit specializations and definitions
      CWG 441C++98non-local references with static storage duration were
      not always initialized before dynamic initializations
      considered as static initialization, always
      initialized before dynamic initializations
      CWG 1415C++98a block-scopeextern variable
      declaration could be a definition
      prohibited (no initializer
      allowed in such declarations)
      CWG 2599C++98it was unclear whether evaluating function
      arguments in the initializer is part of initialization
      it is part of initialization

      [edit]See also

      C documentation forInitialization
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/initialization&oldid=178911"

      [8]ページ先頭

      ©2009-2025 Movatter.jp