c++ - std::initializer_list 和元素的求值顺序

标签 c++ c++11 initializer-list sequence-points

逗号 ( , ) 是 std::initializer_list 中的序列点吗?


示例:这是否是 UB:

#include <vector>

int main() 
{
    auto nums = []
    {
        static unsigned x = 2;
        return ( x++ % 2 ) + 1;
    };

    std::vector< int > v{ nums(), nums(), nums(), nums(), nums() };
    // not sure if this is different: (note the additional brackets)
    // std::vector< int > v({ nums(), nums(), nums(), nums(), nums() });
    for( auto i : v )
    {
        std::cout << i;
    }

    return 0;
}

最佳答案

根据 C++11 § 8.5.4 [dcl.init.list] 第 4 段:

4 Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions (14.5.3), are evaluated in the order in which they appear. That is, every value computation and side effect associated with a given initializer-clause is sequenced before every value computation and side effect associated with any initializer-clause that follows it in the comma-separated list of the initializer-list.

据我所知,GCC 4.8.1 有一个与初始值设定项评估相关的错误。我在这里描述了

http://cpp.forum24.ru/?1-3-0-00000063-000-0-0-1378892425

虽然文本是用俄语写的,但可以使用谷歌翻译等简单地将其翻译成英语。

关于c++ - std::initializer_list 和元素的求值顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20266153/

相关文章:

c++ - C++11 标准是否要求通过常量 unordered_container 的两次迭代以相同的顺序访问元素?

c++ - 使用 bind() 时,即使不使用 ref() 适配器,参数也会通过引用传递

c++ - std::initializer_list<int const> 不能从 std::initializer_list<int> 构造

c++ - "multiple definition of ..."使用arpackpp

c++ - 依赖隐式声明的 move 构造函数是否安全?

c++ - X宏重新定义

c++ - 将任何类型的表达式放在 C++ 的初始化列表中在语法上是否正确?

c++ - 在 C++03 中建模初始值设定项列表

c++ - 如何使用MFC从文件加载图像

c++ - 用户在“控制面板”->“区域和语言选项”中更改设置后修改主窗口的区域设置