c++ 11中列表初始化的优点
Advantages of list initialization in C++11
到目前为止,我发现了以下列表初始化的用法(又名统一初始化)。
1) Introduction之前是list initialization feature
int a=3.3f; // ouch fractional part is automatically truncated
但是在c++ 11中
int a{3.3f}; // compiler error no implicit narrowing conversion allowed
2)动态数组元素可以静态初始化。例如,这个程序在c++ 03中无效,但在c++ 11中有效:
#include <iostream>
int main()
{
int* p=new int[3]{3,4,5};
for(int i=0;i<3;i++)
std::cout<<p[i]<<' ';
delete[] p;
}
它解决了大多数令人烦恼的解析问题
如果你能告诉我列表初始化的其他优点就更好了。除了上面的3之外,列表初始化还有什么优点吗?
非常感谢您的回答
您没有提到的一个重要优点是它在模板元编程中的有用性,现在您可以使用模板计算一些东西,然后在constexpr函数中展开一些模板数据结构并将结果存储在数组中。
参见下面的例子:在编译时使用Constexpr填充数组
代码中:
template<unsigned... Is>
constexpr Table MagicFunction(seq<Is...>){
return {{ whichCategory(Is)... }};
}
我不确定你是否认为它是一个单独的功能,但相同的语法也用于重载std::initializer_list
上的构造函数,它允许你直接初始化STL容器:
std::map<std::string, std::string> m{{"foo", "bar"}, {"apple", "pear"}};
std::cout << m["foo"] << std::endl;
相关文章:
- C++类 - 初始化列表 - 递归 - 按值传递
- 在初始化列表之外手动调用基类的构造函数
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- std::map与谓词与初始化列表
- 类内初始化与构造函数初始化列表的顺序
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- C++初始化列表与分配值
- C++初始化列表中的向量集大小或调整大小
- 在构造函数初始化列表中使用 std::variant
- emplace_back初始化列表错误,当初始化列表在独立变量上工作时
- 解释了构造函数成员初始化列表
- 使用初始化列表时如何获取私有数据?
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 如何在成员初始化列表中声明共享指针
- 庞大的初始化列表,如何修复"fatal error C1060: compiler is out of heap space"
- 我可以检查初始化列表中设置的构造函数主体中的变量吗
- 使用整数初始化列表初始化长双精度的向量
- 是否可以在C++中使用初始化列表设置数组的特定成员?