简体   繁体   中英

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. By using reinterpret_cast, I can avoid allocation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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