3

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

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)它解决了最棘手的解析问题

如果您告诉我列表初始化的其他优点会更好。除了上述3之外,列表初始化还有什么优势吗?

非常感谢您的回答。

4

2 回答 2

4

我不确定您是否认为它是一个单独的功能,但相同的语法也用于重载std::initializer_list允许您直接初始化 STL 容器的构造函数:

std::map<std::string, std::string> m{{"foo", "bar"}, {"apple", "pear"}};
std::cout << m["foo"] << std::endl;
于 2015-09-08T17:42:15.437 回答
4

您没有提到的一个显着优势是它在模板元编程中的有用性,您现在可以使用模板计算某些东西,然后在 constexpr 函数中扩展一些模板数据结构并将结果存储在数组中。

例如,请参见此处:在编译时使用 Constexpr 填充数组

在代码中:

template<unsigned... Is>
constexpr Table MagicFunction(seq<Is...>){
  return {{ whichCategory(Is)... }};
}

我认为在 C++11 之前没有任何方法可以做类似的事情。

于 2015-09-08T17:28:11.910 回答