繁体   English   中英

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

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

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

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

暂无
暂无

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

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