c++ - 这是在序列点之间对同一对象的多次访问定义明确的行为吗?

标签 c++ language-lawyer

是否允许多次访问?

#include <iostream>

int main()
{
    int A[1];
    A[0] = 0;
    A[A[0]] = 1;
    std::cout << A[0];
}

引用以下段落...

Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

如果这使用 A[0] 的旧值,它应该是未定义的行为,对吧?

最佳答案

是的,它是有效的。

首先,在作业的 LHS 上读取 A[0] 是完全有效且定义明确的,原因与此相同:

int x = 42;
x = x + 1;

在执行赋值之前,必须对两个操作数求值。

其次,孤立地评估 A[A[0]] 非常好:

[C++11: 1.9/15]: [..] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. [..]

在 C++03 中,我能找到的最接近相关的措辞是关于赋值的以下内容(尽管在 gaff 中有诸如 a = a + x 之类的构造示例):

[C++03: 5.17/8]: If the value being stored in an object is accessed from another object that overlaps in any way the storage of the first object, then the overlap shall be exact and the two objects shall have the same type, otherwise the behavior is undefined.

关于c++ - 这是在序列点之间对同一对象的多次访问定义明确的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29215437/

相关文章:

c++ - Friend 模板函数类内定义

c++ - 对齐说明符 : on the type/on the member data

c - C 标准库中包含什么?

c++ - 如何使用时间戳和严重性字符串?

条件语句中的 C++ 模板类初始化

c++ - g++ 和 clang++ 自动参数模板特化的不同行为

c++ - 理论上,C++ 实现能否并行计算两个函数参数?

c++ - 智能感知无法在 C++ 中打开源文件 ".tlb"

c++ - 用于存储坐标的 float 或整数

c++ - 在Visual Studio 2012中重建时出现奇怪的链接错误