gpt4 book ai didi

c++ - 严格别名是否会阻止您通过不同类型写入 char 数组?

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:36 25 4
gpt4 key购买 nike

我的理解是 C++ 中的严格别名定义在 basic.lval 11 中:

(11) 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:

  • (11.1) the dynamic type of the object,
  • (11.2) a cv-qualified version of the dynamic type of the object,
  • (11.3) a type similar (as defined in conv.qual) to the dynamic type of the object,
  • (11.4) a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • (11.5) a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • (11.6) an aggregate or union type that includes one of the aforementioned types among its elements or non-static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
  • (11.7) a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
  • (11.8) a char, unsigned char, or std​::​byte type.

根据我的阅读,根据 11.8,这始终是合法的,因为程序通过 unsigned char 类型的左值访问 x 的存储值:

int x = 0xdeadbeef;
auto y = reinterpret_cast<unsigned char*>(&x);
std::cout << y[1];

我很好奇使用别名指向 unsigned char 数组的指针:

alignas(int) unsigned char[4] x;
auto y = reinterpret_cast<int*>(x);
*y = 0xdeadbeef;

这是否违反了严格的别名?我的阅读是它不是,但是我刚刚在另一个线程上被告知它是。仅根据 basic.lval,在我看来没有 UB,因为程序不会尝试访问存储的值:它存储一个新值而不读取它,只要后续读取使用 x,则不会发生违规。

最佳答案

关于“访问”的定义:

http://eel.is/c++draft/defns.access

3.1 access [defns.access]
⟨execution-time action⟩ read or modify the value of an object

换句话说,存储值也是“访问”。还是UB。

关于c++ - 严格别名是否会阻止您通过不同类型写入 char 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51718170/

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