Accessing an array as a struct vs undefined behavior

故事扮演 提交于 2019-12-23 22:54:02

问题


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

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;
}

Compile and run online: http://cpp.sh/6y7m


回答1:


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.

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

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:

— the dynamic type of the object,

— 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,

— 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),

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

— a char or unsigned char type.



来源:https://stackoverflow.com/questions/37211298/accessing-an-array-as-a-struct-vs-undefined-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!