Is it undefined behavior to `reinterpret_cast` a `T*` to `T(*)[N]`?

后端 未结 2 1143
走了就别回头了
走了就别回头了 2020-12-25 12:04

Consider the following scenario:

std::array a;
auto p = reinterpret_cast(a.data());
(*p)[0] = 42;

Is this

2条回答
  •  清歌不尽
    2020-12-25 12:46

    Yes the behaviour is undefined.

    int* (the return type of a.data()) is a different type from int(*)[8], so you are breaking strict aliasing rules.

    Naturally though (and this is more for the benefit of future readers),

    int* p = a.data();
    

    is perfectly valid, as is the ensuing expression p + n where the integral type n is between 0 and 8 inclusive.

提交回复
热议问题