std::initializer_list in C++
目录
Table of Contents
本文为摘录(或转载),侵删,原文为: https://www.cppstories.com/2023/initializer_list_improvements/
1 Referencing local array
std::initializer_list
在使用中会转化成为常量对象的匿名局部数组:
|
|
The above code is equivalent to the following:
|
|
如果尝试编译的话,会出错:
|
|
结论:
std::initializer_list
是一种 “view” type- 他引用一个局部的常量数组 it references some implementation-dependent and a local array of const values.
- Use it mainly for passing into functions when you need a variable number of arguments of the same type.
- If you try to return such lists and pass them around, then you risk lifetime issues
2 The cost of copying elements
通过初始化列表来传递参数很方便,但最好知道,当向 vector 中传递对象时候,vector 中的每个元素都会进行一次拷贝构造,应该了解其代价。