gpt4 book ai didi

c++ - 通过 C 强制转换访问结构的第一个字段是否违反了严格的别名?

转载 作者:IT老高 更新时间:2023-10-28 22:25:54 25 4
gpt4 key购买 nike

此代码是否违反严格别名?

struct {int x;} a;
*(int*)&a = 3

更抽象地说,只要原始读/写操作类型正确,在不同类型之间进行强制转换是否合法?

最佳答案

首先,在 C 中强制转换是合法的。§6.7.2.1/13:

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

别名规则如下(§6.5/7):

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

  • a type compatible with the effective type of the object,
  • a qualified version of a type compatible with the effective type of the object,
  • a type that is the signed or unsigned type corresponding to the effective type of the object,
  • a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
  • a character type.

在这里,您将通过“与对象的有效类型兼容的类型”和“在其成员中包含上述类型之一的聚合或 union 类型”的指针访问它,因此别名也没有问题。所以在 C 中,通过将指向结构的指针转换为相关成员的类型来访问结构的第一个成员确实是完全合法的。

然而,在 C++ 中,您经常会在 C++ 对象的开头找到 vtable 和其他内容。但是,在您的特定情况下,您的结构是标准布局,因此这是明确允许的(n3290 中的第 9.2/20 节,感谢 Luc Danton!-C++03 显然有类似的规则,以 POD 对象表示) .

关于c++ - 通过 C 强制转换访问结构的第一个字段是否违反了严格的别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9747010/

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