c++ - 构造函数参数的求值顺序

标签 c++ c++11

<分区>

假设我有这个类:

struct A
{
  A(int, int, int) {}
};

然后我这样初始化它:

A{ a(), b(), c() };

其中函数a()b()c() 都返回int。应该在 b() 之前调用 a() 和在 c() 之前调用 b() 吗?

我对标准 (8.5.4 [dcl.init.list] p4) 中的以下段落感到困惑:

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. [ Note: This evaluation ordering holds regardless of the semantics of the initialization; for example, it applies when the elements of the initializer-list are interpreted as arguments of a constructor call, even though ordinarily there are no sequencing constraints on the arguments of a call. — end note ]

根据引用,函数将按它们出现的顺序被调用,但是当我用我的编译器 (g++-4.8.1) 测试它时,它不成立。我是不是误会了什么?

最佳答案

这是一个 bug in GCC (感谢 Casey 的链接)。您引用的段落通常适用于列表初始化,其中术语在第 8.5.4/1 段中定义得非常清楚:

List-initialization is initialization of an object or reference from a braced-init-list. Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list.

没有理由相信这只适用于初始化列表构造函数的调用。此外,您引用的段落中的说明澄清了:

This evaluation ordering holds regardless of the semantics of the initialization; for example, it applies when the elements of the initializer-list are interpreted as arguments of a constructor call, even though ordinarily there are no sequencing constraints on the arguments of a call.

关于c++ - 构造函数参数的求值顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17381573/

相关文章:

c++ - C++ 中具有可变参数签名的函数映射

c++ - 有没有 Winapi 方法可以将文件移动到回收站?

c++ - 使用 GetDIBits 函数对 _imp__GetDIBits@28 的 undefined reference

c++ - 所有 STL 容器的通用哈希函数

c++ - 使用仿函数模板实现自定义比较器

c++ - 设置一个 std::function 变量来引用 std::sin 函数

c++ - 仅包括来自 libpcap 的必要函数

c++ - shared_ptr<> 的自定义删除器给出 'no context error'

C++二进制搜索没有成功运行......永远

c++ - MinGW 4.7.2 与 Visual C++ 11.0 (2012) 基准测试