Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      Default-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
       
       

      This is the initialization performed when an object is constructed with no initializer.

      Contents

      [edit]Syntax

      T object ; (1)
      newT (2)

      [edit]Explanation

      Default-initialization is performed in three situations:

      1) when a variable with automatic, static, or thread-localstorage duration is declared with no initializer;
      2) when an object with dynamic storage duration is created by anew-expression with no initializer;
      3) when a base class or a non-static data member is not mentioned in aconstructor initializer list and that constructor is called.

      The effects of default-initialization are:

      • ifT is a (possibly cv-qualified)non-POD(until C++11) class type, the constructors are considered and subjected tooverload resolution against the empty argument list. The constructor selected (which is one of thedefault constructors) is called to provide the initial value for the new object;
      • ifT is an array type, every element of the array is default-initialized;
      • otherwise, no initialization is performed (seenotes).

      [edit]Default-initialization of a const object

      If a program calls for the default-initialization of an object of aconst-qualified typeT, T shall be aconst-default-constructible class type or array thereof.

      A class typeT is const-default-constructible if default-initialization ofT would invoke a user-provided constructor ofT(not inherited from a base class)(since C++11) or if

      Only (possibly cv-qualified) non-POD class types (or arrays thereof) with automatic storage duration were considered to be default-initialized when no initializer is used. Scalars and POD types with dynamic storage duration were considered to be not initialized (since C++11, this situation was reclassified as a form of default-initialization).

      (until C++11)
      • each direct non-static data memberM ofT is of class typeX (or array thereof),X is const-default-constructible, and
      • T has no directvariant members, and
      (until C++11)
      • each direct non-variant non-static data memberM ofT has adefault member initializer or, ifM is of class typeX (or array thereof),X is const-default-constructible,
      • ifT is a union with at least one non-static data member, exactly onevariant member has a default member initializer,
      • ifT is not a union, for each anonymous union member with at least one non-static data member (if any), exactly one non-static data member has a default member initializer, and
      (since C++11)

      eachpotentially constructed base class ofT is const-default-constructible.

      [edit]Indeterminate and erroneous values

      When storage for an object with automatic or dynamic storage duration is obtained, the object has anindeterminate value.

      If no initialization is performed for an object, that object retains an indeterminate value until that value is replaced.

      (until C++26)

      When storage for an object with automatic or dynamic storage duration is obtained, the bytes comprising the storage for the object have the following initial value:

      • If the object has dynamic storage duration, or is the object associated with a variable orfunction parameter whose first declaration is marked with[[indeterminate]], the bytes haveindeterminate values.
      • Otherwise, the bytes haveerroneous values, where each value is determined by the implementation independently of the state of the program.

      If no initialization is performed for an object (includingsubobjects), such a byte retains its initial value until that value is replaced.

      • If any bit in thevalue representation has an indeterminate value, the object has anindeterminate value.
      • Otherwise, if any bit in the value representation has an erroneous value, the object has anerroneous value.
      (since C++26)

      If an evaluation produces an indeterminate value, the behavior isundefined.

      If an evaluation produces an erroneous value, the behavior iserroneous.

      (since C++26)

      [edit]Special cases

      The following types areuninitialized-friendly:

      (since C++17)
      • unsignedchar
      • char, if its underlying type isunsignedchar

      Given an indeterminate or erroneous(since C++26) valuevalue, theuninitialized result value ofvalue is:

      • An indeterminate value, ifvalue is also an indeterminate value.
      • value, ifvalue is an erroneous value.
      (since C++26)

      If an evaluationeval produces an indeterminate or erroneous(since C++26) valuevalue of an uninitialized-friendly type, the behavior is well-defined in the following cases:

      • eval is the evaluation of one of the following expressions and operands:
      In this case, the result of the operation is the uninitialized result value ofvalue.
      • eval is an evaluation of the right operand of asimple assignment operator whose left operand is an lvalue of an uninitialized-friendly type.
      In this case, the value of the object referred to by the left operand is replaced by the uninitialized result value ofvalue.
      • eval is the evaluation of the initialization expression when initializing an object of an uninitialized-friendly type.
      (since C++17)
      In this case, that object is initialized to the uninitialized result value ofvalue.

      Converting an indeterminate value of an uninitialized-friendly type produces an indeterminate value.

      Converting an erroneous value of an uninitialized-friendly type produces an erroneous value, the result of the conversion is the value of the converted operand.

      (since C++26)
      // Case 1: Uninitialized objects with dynamic storage duration// All C++ versions: indeterminate value + undefined behaviorint f(bool b){unsignedchar* c= newunsignedchar;unsignedchar d=*c;// OK, “d” has an indeterminate valueint e= d;// undefined behaviorreturn b? d:0;// undefined behavior if “b” is true} // Case 2: Uninitialized objects with automatic storage duration// until C++26: indeterminate value + undefined behavior// since C++26: erroneous value + erroneous behaviorint g(bool b){unsignedchar c;// “c” has an indeterminate/erroneous value unsignedchar d= c;// no undefined/erroneous behavior,// but “d” has an indeterminate/erroneous value assert(c== d);// holds, but both integral promotions have// undefined/erroneous behavior int e= d;// undefined/erroneous behaviorreturn b? d:0;// undefined/erroneous behavior if “b” is true} // Same as case 2void h(){int d1, d2;// “d1” and “d2” have indeterminate/erroneous valuesint e1= d1;// undefined/erroneous behaviorint e2= d1;// undefined/erroneous behavior assert(e1== e2);// holdsassert(e1== d1);// holds, undefined/erroneous behaviorassert(e2== d1);// holds, undefined/erroneous behavior // no undefined/erroneous behavior,// but “d2” has an indeterminate/erroneous valuestd::memcpy(&d2,&d1, sizeof(int)); assert(e1== d2);// holds, undefined/erroneous behaviorassert(e2== d2);// holds, undefined/erroneous behavior}

      [edit]Notes

      References and const scalar objects cannot be default-initialized.

      Feature-test macroValueStdFeature
      __cpp_constexpr201907L(C++20)Trivial default-initialization andasm-declaration inconstexpr functions

      [edit]Example

      Run this code
      #include <string> struct T1{int mem;}; struct T2{int mem;    T2(){}// “mem” is not in the initializer list}; int n;// static non-class, a two-phase initialization is done:// 1) zero-initialization initializes n to zero// 2) default-initialization does nothing, leaving n being zero int main(){[[maybe_unused]]int n;// non-class, the value is indeterminatestd::string s;// class, calls default constructor, the value is ""std::string a[2];// array, default-initializes the elements, the value is {"", ""}//  int& r;           // Error: a reference//  const int n;      // Error: a const non-class//  const T1 t1;      // Error: const class with implicit default constructor[[maybe_unused]]    T1 t1;// class, calls implicit default constructorconst T2 t2;// const class, calls the user-provided default constructor// t2.mem is default-initialized}

      [edit]Defect reports

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

      DRApplied toBehavior as publishedCorrect behavior
      CWG 178C++98there was no value-initialization;
      empty initializer invoked default-initialization
      (thoughnew T() also performs zero-initialization)
      empty initializer invokes
      value-initialization
      CWG 253C++98default-initialization of a const object could not
      call an implicitly declared default constructor
      allowed if all subobjects are initialized
      CWG 616C++98lvalue to rvalue conversion of any
      uninitialized object was always UB
      indeterminateunsignedchar is allowed
      CWG 1787C++98read from an indeterminateunsignedchar
      cached in a register was UB
      made well-defined

      [edit]See also

      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/default_initialization&oldid=171164"

      [8]ページ先頭

      ©2009-2025 Movatter.jp