gpt4 book ai didi

c++ - 编译器指令重新排序

转载 作者:太空宇宙 更新时间:2023-11-04 14:34:32 26 4
gpt4 key购买 nike

struct Vec
{
double x, y, z;
};

Vec vec;
vec.x = 1.0;
vec.y = 2.0;
vec.z = 3.0;
double res = (&vec.x)[2]; // (&vec.x)[2] should be equal to vec.z

变量 res 的值应该等于 3。但是当我打开优化时,编译器错误地重新排序指令并且 res 包含一些垃圾。一些可能的重新排序示例:

vec.x = 1.0;
vec.y = 2.0;
vec.z = 3.0;
res = (&vec.x)[2]; // correct value

vec.x = 1.0;
vec.y = 2.0;
res = (&vec.x)[2]; // incorrect value
vec.z = 3.0;

vec.x = 1.0;
res = (&vec.x)[2]; // incorrect value
vec.y = 2.0;
vec.z = 3.0;

这是编译器的错误吗?还是不允许这样访问结构数据成员?

编辑:

我刚刚意识到之前的代码确实有效,对此感到抱歉。但这不起作用:

Vec vec;
vec.x = 1.0;
vec.y = 2.0;
vec.z = 3.0;
double res = (&vec.x)[i]; // (&vec.x)[i] should be equal to vec.z when i == 2

当变量 i 在编译时未知时,编译器会错误地重新排序指令。

最佳答案

您正在调用未定义的行为。 (&vec.x)[2] 等同于 (&vec.x) + 2,标准 (§[expr.add]/4) 具有以下内容说说指针加法(强调我的):

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object84, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

另请参阅上面引用的注释 84:

84) An object that is not an array element is considered to belong to a single-element array for this purpose; see 5.3.1.

由于vec.x不是数组,所以它被认为是单元素数组的一个元素。因此 vec.xvec.z 不是同一数组的元素,并且行为未定义。

关于c++ - 编译器指令重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38089644/

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