c++ 11中列表初始化的优点

Advantages of list initialization in C++11

本文关键字:初始化 列表 c++      更新时间:2023-10-16

到目前为止,我发现了以下列表初始化的用法(又名统一初始化)。

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;