xml*_*lmx 3 c++ standards initialization c++20 default-initialization
以下来自指定初始值设定项的cppref:
struct A { int x; int y; int z; };
A b{.x = 1, .z = 2}; // ok, b.y initialized to 0
Run Code Online (Sandbox Code Playgroud)
默认情况下,所有基本类型在 C++ 中都是默认初始化的,而不是零初始化的。
为什么指定的初始化器会对数据成员进行零初始化?
b.y将从空的初始值设定项列表进行初始化,其效果是零初始化为0。
对于非联合聚合,当初始化器子句的数量小于成员数量时,未提供指定初始化器的元素的初始化方式与上述相同(如果提供了默认成员初始化器,则为空列表初始化) :
Run Code Online (Sandbox Code Playgroud)struct A { string str; int n = 42; int m = -1; }; A{.m=21} // Initializes str with {}, which calls the default constructor // then initializes n with = 42 // then initializes m with = 21
根据标准,[dcl.init.aggr]/5:
对于非联合聚合,每个不是显式初始化元素的元素都按如下方式初始化:
(5.1) 如果元素具有默认成员初始值设定项 ( [class.mem] ),则从该初始值设定项初始化该元素。
(5.3) 否则,程序是格式错误的。
| 归档时间: |
|
| 查看次数: |
962 次 |
| 最近记录: |