【发布时间】:2013-05-03 18:11:42
【问题描述】:
这是测试代码:
#include <stdio.h>
struct test
{
int m[1];
};
struct test2: public test
{
int m1[22];
void set(int x, int y) { m[x] = y; }
};
int main()
{
test2 t;
t.m[1] = 123;
t.set(0, 0);
t.set(1, 1);
printf("%d %d\n", t.m[0], t.m[1]);
return 0;
}
我编译一次没有优化:
$ g++ -O0 testf.cpp
$ ./a.out
0 1
$ g++ -O2 testf.cpp
$ ./a.out
1 123
在我看来,gcc 看到数组大小 m[1] 并优化对它的访问以始终访问第一个元素 m[0]。问题是:是优化错误还是某些 C++ 规则被破坏了,因此 gcc 可以做它所做的事情,如果是,那么什么规则?
请注意,由于额外的 m1[22] 内存(实际应用程序中的设计),不会发生内存/堆栈溢出。我不问这是否是一种好的编程风格,我只是想得到上述问题的正确答案。
更新:我接受了带有 std 详细信息的答案,但最大的帮助是带有以下链接的评论:Is the "struct hack" technically undefined behavior?
【问题讨论】:
-
作为测试,如果你写
void set(int x, int y) { x[(int*)m] = y; },那么麻烦的优化就停止了吗?我怀疑这会将其从“数组对象访问”更改为“取消引用有效但不安全派生的指针值”。 -
不,只有当我这样做时(volatile int*)。
标签: c++ optimization gcc g++