假设我想引用我已经定义的 initializer_list
的成员。我可以做吗?
此代码编译并给出预期的结果:“13 55”在 Visual Studio 和 gcc 中,我只想知道它是合法的:
const int foo[2] = {13, foo[0] + 42};
Say I want to refer to a member of an initializer_list
that I already defined. Can I do it?
This code compiles and gives the expected: "13 55 " in both Visual Studio and gcc, I'd just like to know that it's legal:
const int foo[2] = {13, foo[0] + 42};
发布评论
评论(1)
因此,我们在这里拥有的是C ++标准草案的
8.5.1
中介绍的汇总初始化,并说:和:
尽管似乎合理的是初始化骨料的每个成员的副作用应在下一个之前进行测序,因为初始化器列表中的每个元素都是完整的表达式。该标准实际上并不能保证这一点,我们可以从说:
还要注意:
我们可以从相关的理查德·史密斯说:
因此,目前尚未由标准指定,不能依靠这一点,尽管如果一个实现未按照您的期望来对待它,我会感到惊讶。
对于这样的简单情况,与此类似的简单情况似乎是一种更好的选择:
C ++ 17
提案p0507r0:核心问题1343:非阶级初始化的测序澄清提出的完整表达点在这里全表达的评估。因此,这并没有改变这是未指定的。
这个问题的相关更改在 [Into.execution] :
和 [Into.execution] p12 :
因此,在这种情况下em>。这是从认为他们每个人都是自己的全表达。
C ++ 20的更改
指定的初始化建议:p0329 包含以下添加的添加,似乎可以很好地定义:
我们可以看到这反映在最新草稿标准中。
So what we have here is aggregate initialization covered in section
8.5.1
of the draft C++ standard and it says:and:
Although it seems reasonable that side effects from initializing each member of the aggregate should be sequenced before the next, since each element in the initializer list is a full expression. The standard does not actually guarantee this we can see this from defect report 1343 which says:
and also notes:
and we can see from a related std-discussion topic Richard Smith says:
So this is currently not specified by the standard and can not be relied upon, although I would be surprised if an implementation did not treat it the way you expect.
For a simple case like this something similar to this seems a better alternative:
Changes In C++17
The proposal P0507R0: Core Issue 1343: Sequencing of non-class initialization clarifies the full-expression point brought up here but does not answer the question about whether the side-effect of initialization is included in the evaluation of the full-expression. So it does not change that this is unspecified.
The relevant changes for this question are in [intro.execution]:
and [intro.execution]p12:
So in this case both
13
andfoo[0] + 42
are constituent expression which are part of a full-expression. This is a break from the analysis here which posited that they would each be their own full-expressions.Changes In C++20
The Designated Initialization proposal: P0329 contains the following addition which seems to make this well defined:
We can see this is reflected in the latest draft standard.