C++编程法则365条一天一条(359)认识各种初始化术语
文章目录
-
- Default initialization默认初始化
- Copy initialization拷贝初始化
- 聚合初始化
参考:
https://en.cppreference.com/w/cpp/language/copy_initialization
https://en.cppreference.com/w/cpp/language/default_initialization
https://en.cppreference.com/w/cpp/language/aggregate_initialization
Default initialization默认初始化
T object ; (1)
new T (2)
当未指定初始化器时,就叫默认初始化。
除了以上显示定义的场景之外,基类、非静态成员没有指定初始化器时,都属于默认初始化。
如果T是对象类型,那么将调用默认构造进行初始化,非对象类型将按照生命周期的不同走不同策略(例如堆栈变量,不做任何初始化操作,其值不确定;对于静态、线程、全局变量,初始化为0)。
需要注意的是,如果是const对象进行默认初始化,chus需要用户提供一个默认构造函数,编译器提供的默认构造不做数,否则编译报错:
default initialization of an object of const type 'const T1' without a user-provided default constructor
#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 zeroint main()
{int n; // non-class, the value is indeterminatestd::string s; // class, calls default ctor, the value is "" (empty string)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 ctorT1 t1; // class, calls implicit default ctorconst T2 t2; // const class, calls the user-provided default ctor// t2.mem is default-initialized (to indeterminate value)
}
Copy initialization拷贝初始化
用一个对象初始化另一个对象,叫做拷贝初始化,不一定是拷贝构造,也可能是构造。
T object = other; (1)
T object = {other}; (2) (until C++11)
f(other) (3)
return other; (4)
throw object;
catch (T object) (5)
T array[N] = {other-sequence}; (6)