c++ - 用逗号相互依赖初始化?

标签 c++ c++11 initialization language-lawyer undefined-behavior

下面是否完美定义:

int x = 42, y = x;

即严格等价于:

int x = 42;
int y = x;

编辑:问题与风格无关(我知道这是错误的......),问题是“理论上的”

最佳答案

正确答案是

int x = 42, y = x;

int x = 42;
int y = x;

通常是等价的(不严格)。


考虑到标准 § 8 声明符 [dcl.decl]:

3 Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.

并在脚注[100]中进一步说明:

A declaration with several declarators is usually equivalent to the corresponding sequence of declarations each with a single declarator. That is

T D1, D2, ... Dn;

is usually equivalent to

T D1; T D2; ... T Dn;

where T is a decl-specifier-seq and each Di is an init-declarator.

  • 以上保证 x = 42y = x 将被单独评估。然而,作为@Praetorian在评论中正确指出,脚注不规范。

  • 这意味着评估的顺序没有明确定义,实现者也可以以相反的顺序实现声明的评估(即。T Dn; ...T D2; T D1;).

  • 有人可能会争辩说,逗号运算符可以保证从左到右求值。然而,事实并非如此。根据 K & R [K & R II, 3.6 p.63],这也适用于 C++:

The commas that separate function arguments, variables in declarations, etc., are not comma operators, and do not guarantee left to right evaluation.

关于c++ - 用逗号相互依赖初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24224115/

相关文章:

c++ - 无法在动态链接库 libstdc++-6.dll 中定位过程入口点 _gxx_personality_v0 错误

c++ - 使用 std::string 时出现 bad_alloc 错误

c++ - 是否可以使用 c++11 中的模板元编程创建一个填充大小为 N 的零的 vector

c++ - 在 Windows 7 上使用带有代码块的 clang

c++ - 使用类似策略模式的文件解析器 - 如何获得结果?

c++ - 移除 std::future 和 std::promise 的无效特化

c++ - 是否存在 int 成员保证零初始化的情况?

php - 在php中使用自定义类初始化静态成员

hibernate:LazyInitializationException:无法初始化代理

c# - 我可以将 IL2CPP(C++ 中间语言)用于非 Unity 应用程序吗?