简体   繁体   English

将指针转换为数组指针是否有效

[英]Is it valid to cast pointer to struct to array pointer

Given an aggregate struct/class in which every member variable is of the same data type: 给定一个聚合结构/类,其中每个成员变量具有相同的数据类型:

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

How valid is it to cast it to an array of its members? 将它投射到其成员数组的有效性如何? eg 例如

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());

I am doing this because in most cases I need named member access for clarity, whereas in some other cases I need to pass the an array into some other API. 我这样做是因为在大多数情况下我需要命名成员访问以获得清晰度,而在其他一些情况下我需要将一个数组传递给其他API。 By using reinterpret_cast, I can avoid allocation. 通过使用reinterpret_cast,我可以避免分配。

The cast it not required to work by the standard. 演员不需要按标准工作。

However, you can make your code safe by using static asserts that will prevent it from compiling if the assumptions are violated: 但是,您可以使用静态断言使代码安全,如果违反了假设,则静态断言将阻止编译:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM