将数组作为结构访问与未定义行为 [英] Accessing an array as a struct vs undefined behavior

查看:89
本文介绍了将数组作为结构访问与未定义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个包含4个float值的结构和一个包含4个元素的float数组.

Let's say we have this structure with 4 float values and a float array with 4 elements.

然后是否以未定义的行为作为Foo实例访问数组并通过该实例更改数组元素?

Is it then undefined behavior or not to access the array as a Foo instance and change the array elements through that instance?

struct Foo
{
    float a;
    float b;
    float c;
    float d;
};

float values[4] = { 1.0f, 1.0f, 1.0f, 1.0f };

int main()
{
    auto& floats = *reinterpret_cast<Foo*>(values);
    floats.a = 0.0f;
    floats.b = 0.0f;
    floats.c = 0.0f;
    floats.d = 0.0f;
}

编译并在线运行: http://cpp.sh/6y7m

推荐答案

是的,这确实是未定义的行为.它违反了所谓的严格别名规则-禁止通过 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.

这篇关于将数组作为结构访问与未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆