c++ - 在 C++11 中使用严格别名时,它是否定义为_write_ 到 char*,然后从别名 nonchar* _read_?

标签 c++ c++11 strict-aliasing

有很多关于严格别名的讨论(特别是“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 or unsigned 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/

相关文章:

c++ - 使用 std::transform 将 std::vector 容器转换为 std::set

C++11:如果不为 std::thread 调用 join() 会发生什么

node.js - (如何)我应该销毁 uv_async_t 吗?

c - 棘手的指针别名问题

c++ - 什么时候出队大小调用不是线程安全的?

c++ - 在什么情况下我应该考虑实现移动构造函数和移动运算符?

c++ - 将 freeglut 回调包装在一个类中的最优雅的方式

c++ - 浮点位和严格的别名

c++ - `make_unique` 相对于普通构造函数的优势?

c++ - 增加数组的大小会产生一些问题