且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数组作为结构访问与未定义行为

更新时间:2023-11-12 09:55:10

是的,这确实是未定义的行为.它违反了所谓的严格别名规则-禁止通过 unrelated 指针访问对象(除非特别要求,我不会在这里详述 unrelated 的详细信息)

Yes, it is an undefined behavior indeed. It violates so-called strict aliasing rule - which prohibits access to the object through unrelated pointer (I won't dwell into details of what is unrelated here, unless specifically asked).

但是,浮点数组与结构无关.

However, an array of floats to a struct is unrelated.

以下是标准(3.10/10)的摘录:

Here is an extract from Standard (3.10 / 10):

如果程序尝试通过以下方式访问对象的存储值 除以下类型之一以外的glvalue的行为是 未定义:

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:

-对象的动态类型,

-对象的动态类型的cv限定版本,

— a cv-qualified version of the dynamic type of the object,

-类型相似(如 定义为对象的动态类型

— a type similar (as defined in 4.4) to the dynamic type of the object,

-一种类型 与动态类型相对应的有符号或无符号类型 对象

— a type that is the signed or unsigned type corresponding to the dynamic type of the object,

-一种类型,它是与以下类型对应的有符号或无符号类型 对象动态类型的cv限定版本,

— a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,

-包含上述类型之一的集合或联合类型 在其元素或非静态数据成员中(包括递归 子集合或包含的元素或非静态数据成员 联合)

— an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),

-一种类型(可能是经过cv限定)的基类类型 对象的动态类型,

— a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,

-字符或无符号字符类型.

— a char or unsigned char type.