将指向struct的指针强制转换为数组指针是否有效?

Is it valid to cast pointer to struct to array pointer

本文关键字:指针 数组 是否 有效 转换 struct      更新时间:2023-10-16

给定一个聚合结构/类,其中每个成员变量都是相同的数据类型:

struct MatrixStack {
    Matrix4x4 translation { ... };
    Matrix4x4 rotation { ... };
    Matrix4x4 projection { ... };
} matrixStack;

将其强制转换为其成员的数组是否有效?例如

const Matrix4x4 *ptr = reinterpret_cast<const Matrix4x4*>(&matrixStack);
assert(ptr == &matrixStack.translation);
assert(ptr + 1 == &matrixStack.rotation);
assert(ptr + 2 == &matrixStack.projection);
auto squashed = std::accumulate(ptr, ptr + 3, identity(), multiply());

我这样做是因为在大多数情况下,我需要命名成员访问以保持清晰度,而在其他一些情况下,我需要将数组传递给其他一些API。通过使用reinterpret_cast,可以避免分配

该转换不需要按标准工作。

但是,您可以通过使用静态断言来确保代码安全,如果违反了假设,它将阻止编译:

static_assert(sizeof(MatrixStack) == sizeof(Matrix4x4[3]), "Size mismatch.");
static_assert(alignof(MatrixStack) == alignof(Matrix4x4[3]), "Alignment mismatch.");
// ...
const Matrix4x4* ptr = &matrixStack.translation;
// or
auto &array = reinterpret_cast<const Matrix4x4(&)[3]>(matrixStack.translation);