Does Visual C++ support “strict aliasing”?

2019-02-13 13:43发布

I recently was surprised to learn that the C and C++ language standards have a "strict aliasing" rule. In essence, the rule prohibits variables of differing types from referencing the same memory location.

As an example:

char buffer[4] = { 0x55, 0x66, 0x77, 0x88 };
int32 *p = (int32*)&buffer[0]; // illegal because buffer[0] and *p are different types

Most of the professional C++ developers I interact with are not familiar with this rule. Based on my research, it seems to affect mostly GCC/G++/CLANG users. Does Visual C++ support enabling/disabling this rule? If so, how does one do so?

Thank you

1条回答
做个烂人
2楼-- · 2019-02-13 14:03

"Strict aliasing" is a C++ rule restricting programs, not compilers. Since violating the rule is Undefined Behavior, no diagnostic required a compiler doesn't need to support it in any way.

That said, Microsoft is a bit less aggressive in applying optimizations. Only last week have they announced their new optimizer assumes no signed overflow, something that GCC has assumed for a few years already. Strict aliasing is going to break a few Windows headers, so those need fixing first. (A few types act as if they contain unions, but they're not formally defined as such)

查看更多
登录 后发表回答