有很多关于严格别名的讨论(特别是“What is the strict aliasing rule?”和“Strict aliasing rule and 'char *' pointers”),但这是一个我没有看到明确解决的极端情况。
考虑这段代码:
int x;
char *x_alias = reinterpret_cast<char *>(&x);
x = 1;
*x_alias = 2; // [alias-write]
printf("x is now %d\n", x);
打印的值必须反射(reflect) [alias-write] 中的变化吗? (显然有字节序和表示方面的考虑,这不是我关心的问题。)
C++11 规范中著名的 [basic.lval] 子句使用了这种语言(强调我的):
If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:
- ... various other conditions ...
- a
char
orunsigned char
type.
我无法弄清楚“访问”是仅指读取操作(从非字符对象读取字符)还是写入操作(将字符写入非字符对象)。如果规范中有“访问”的正式定义,我找不到,但在其他地方,规范似乎使用“访问”进行读取,使用“更新”进行写入。
这在反序列化时特别有用;将数据直接从连线传输到对象中既方便又高效,不需要从字符缓冲区到对象的中间 memcpy()。
最佳答案
is it defined to _write_ to a char*, then _read_ from an aliased nonchar*?
是的。
Must the printed value reflect the change in [alias-write]?
是的。
严格的别名表示 ((un
)signed
) char*
可以为任何东西起别名。 “访问”一词表示读取和写入操作。
关于c++ - 在 C++11 中使用严格别名时,它是否定义为_write_ 到 char*,然后从别名 nonchar* _read_?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36225493/