代码之家  ›  专栏  ›  技术社区  ›  Destructor

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

  •  3
  • Destructor  · 技术社区  · 9 年前

    到目前为止,我发现 list initialization (也称为统一初始化)。

    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项之外,列表初始化还有什么优点吗?

    非常感谢您的回答。

    2 回复  |  直到 9 年前
        1
  •  4
  •   Community CDub    7 年前

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

    例如,请参见此处: Populate An Array Using Constexpr at Compile-time

    在代码中:

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

    我认为在C++11之前没有任何方法可以做到这一点。

        2
  •  4
  •   mattnewport    9 年前

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

    std::map<std::string, std::string> m{{"foo", "bar"}, {"apple", "pear"}};
    std::cout << m["foo"] << std::endl;