3.1.3 一致性初始化(Uniform initialization)与初值列(Initializer List)

C++ 11引入了“一致性初始化”的概念,使用大括号:

int values[] { 1, 2, 3 };

vector<int> v { 2, 3, 5, 7, 11, 13, 17 };

vector<string> cities { "Berlin", "New York" };

complex<double> c { 4.0, 3.0 };//equivalent to c(4.0, 3.0)

初值列会强迫造成所谓的value initialization,意思是即使某个local变量属于某种基础类型(那通常会有不明确的初值)也会被初始化为0或nullptr:

int i;//i has undefined value

int j {};//j is initialized by 0

int* p;//p has undefined value

int* q {};//q is initialized by nullptr

窄化,也就是精度降低或造成数值变动——对大括号而言是不可成立的。

int x1(5.3);//OK, but x1 becomes 5

int x2 = 5.3;//OK, but x1 becomes 5

int x3 { 5.0 }; //ERROR: narrowing

int x4 = { 5.3 };//ERROR: narrowing

char c1 { 7 };//OK: even though 7 is an int, this is not narrowing

char c2 { 99999 };//ERROR: narrowing (if 99999 doesn't fit into a char)

vector<int> v1 { 1, 2, 4, 5 };//OK

vector<int> v2 { 1, 2.3, 4, 5.6 };//ERROR: narrowing doubles into ints

浮点数转换至整数,永远是一种窄化——即使是7.0转为7。

为了支持“用户自定义类型之初值列”概念,C++ 11提供了class template std::initializer_list<>,用来支持以一系列值进行初始化:

当“指明实参个数”和“指明一个初值列”的构造函数同时存在时,优先使用带有初值列的那个。
explicit构造函数表现:

您还未添加分享代码,请到主题选项中,添加百度分享代码!

您可以选择一种方式赞助本站

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

图片 表情