小编Ben*_*Ben的帖子

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

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

struct MatrixStack {
    Matrix4x4 translation { ... };
    Matrix4x4 rotation { ... };
    Matrix4x4 projection { ... };
} matrixStack;
Run Code Online (Sandbox Code Playgroud)

将它投射到其成员数组的有效性如何?例如

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());
Run Code Online (Sandbox Code Playgroud)

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

c++ struct pointers casting c++11

6
推荐指数
1
解决办法
276
查看次数

标签 统计

c++ ×1

c++11 ×1

casting ×1

pointers ×1

struct ×1