簡體   English   中英

是否可以將 reinterpret_cast unsigned char 數組移植到僅包含 C++ 中的 unsigned chars 成員的結構指針

[英]Is it portable to reinterpret_cast unsigned char array to struct pointer containing only unsigned chars members in C++

我知道使用 reinterpret_cast 將 unsigned char 數組轉換為結構指針可能會導致問題,因為不同系統上的字節填充和排序(如本例中)

struct SomeData
{
    unsigned char first;
    int second;
};

unsigned char data[5];
// SomeData might be more than 5 bytes because of padding
// We can't be sure second is valid, because of bytes ordering
SomeData* someData = reinterpret_cast<SomeData*>(data); 

但我的問題是對於只有 unsigned char 成員的結構

struct RGB
{
    unsigned char r;
    unsigned char g;
    unsigned char b;
};

unsigned char data[3];
RGB* rgbData = reinterpret_cast<RGB*>(data); 

在這種情況下,struct RGB 相當於 unsigned char[3],因此我假設不會有填充。 我已經用 g++ 和 msvc 進行了測試,沒有添加任何填充,這有保證嗎?

雖然reinterpret_cast是明確定義的(因為您可以安全地reinterpret_cast回原始類型),但訪問結構成員是隱含的未定義行為:沒有RGB類型的 object ,因此不能有它的成員可以參考

C 明確且規范地描述了標准將沒有行為描述為未定義行為的情況; C++ 僅暗示注釋中的含義,但它畢竟是“未定義”的詞源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM