C++11中列表初始化的优点
Advantages of list initialization in C++11
到目前为止,我发现了 list initialization 的以下用法(a.k.a。统一初始化)。
1) 介绍之前是列表初始化功能
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) 它解决了most vexing parse问题
如果你告诉我列表初始化的其他优点会更好。除了以上3点,列表初始化还有什么优点吗?
非常感谢您的回答。
你没有提到的一个重要优势是它在模板元编程中的实用性,你现在可以使用模板计算一些东西,然后在 constexpr 函数中扩展一些模板数据结构并将结果存储在数组中。
参见此处的示例:Populate An Array Using Constexpr at Compile-time
代码中:
template<unsigned... Is>
constexpr Table MagicFunction(seq<Is...>){
return {{ whichCategory(Is)... }};
}
我认为在 C++11 之前没有任何方法可以做类似的事情。
我不确定您是否认为它是一个单独的功能,但相同的语法也用于在 std::initializer_list
上重载构造函数,它允许您直接初始化 STL 容器:
std::map<std::string, std::string> m{{"foo", "bar"}, {"apple", "pear"}};
std::cout << m["foo"] << std::endl;
到目前为止,我发现了 list initialization 的以下用法(a.k.a。统一初始化)。
1) 介绍之前是列表初始化功能
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) 它解决了most vexing parse问题
如果你告诉我列表初始化的其他优点会更好。除了以上3点,列表初始化还有什么优点吗?
非常感谢您的回答。
你没有提到的一个重要优势是它在模板元编程中的实用性,你现在可以使用模板计算一些东西,然后在 constexpr 函数中扩展一些模板数据结构并将结果存储在数组中。
参见此处的示例:Populate An Array Using Constexpr at Compile-time
代码中:
template<unsigned... Is>
constexpr Table MagicFunction(seq<Is...>){
return {{ whichCategory(Is)... }};
}
我认为在 C++11 之前没有任何方法可以做类似的事情。
我不确定您是否认为它是一个单独的功能,但相同的语法也用于在 std::initializer_list
上重载构造函数,它允许您直接初始化 STL 容器:
std::map<std::string, std::string> m{{"foo", "bar"}, {"apple", "pear"}};
std::cout << m["foo"] << std::endl;