簡體   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