gpt4 book ai didi

c++ - 增加初始化列表中使用两次的变量 - 未定义的行为?

转载 作者:IT老高 更新时间:2023-10-28 22:17:34 26 4
gpt4 key购买 nike

编辑:尚未回答 - 链接的问题是关于普通 r 值的,如果相关的话,初始化列表是一个单独的概念。

这个语句是否定义良好,或者在初始化列表中使用前缀递增运算符,在列表中出现两次的变量上,未定义的行为?

struct T t = { i, ++i };

我对 ANSI C 最感兴趣,但了解其他版本的 C 和/或 C++ 是否不同也会很有用。如果像下面这样的类似结构是合法的:

struct T t = { i, i++ };

struct T t = { ++i, ++i };

struct T t = { i++, ++i };

struct T t = { i++, i++ };

最佳答案

C++11 及更高版本

list initialization 的行为是明确定义的.根据sequenced-before rules (C++11 起):

10) In list-initialization, every value computation and side effect of a given initializer clause is sequenced before every value computation and side effect associated with any initializer clause that follows it in the brace-enclosed comma-separated list of initalizers.

所以对于 struct T t = { i,++i };, i 将首先被评估,然后 ++i,顺序明确。所有其他样本也可以。

引用 C++ 标准,$8.6.4/4 List-initialization[dcl.init.list] :

(强调我的)

Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions ([temp.variadic]), 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 ]

关于c++ - 增加初始化列表中使用两次的变量 - 未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39340030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com