2011-09-21 30 views
1

如果我已將結構的成員複製到我的類中,我是否可以從我的類投射到結構中?標準佈局類型和reinterpret_cast

#include <stdint.h> 
#include <sys/uio.h> 

class Buffer 
{ 
public: 
    void * address; 
    size_t size; 

    Buffer(void * address = nullptr, size_t size = 0) 
     : address(address), size(size) 
    { 
    } 

    operator iovec *() const 
    { 
     // Cast this to iovec. Should work because of standard layout? 
     return reinterpret_cast<iovec *>(this); 
    } 
} 
+0

你爲什麼需要這門課? –

+2

這絕對不是常量正確的。 –

回答

4

首先,你不能拋棄常量性:

§5.2.10p2。 reinterpret_cast運算符不得拋棄constability(§5.2.11)。 (...)

所以,你至少需要編寫的

operator iovec const*() const 
{ 
    return reinterpret_cast<iovec const*>(this); 
} 

operator iovec *() 
{ 
    return reinterpret_cast<iovec *>(this); 
} 

最重要的是,你需要有兩個Bufferiovec是標準-layout類型,並且iovec不能具有比Buffer更嚴格的對齊(即更大)。

§5.2.10p7。一個對象指針可以顯式轉換爲一個不同類型的對象指針 。當prvalue類型的v「指針T1」是 轉換爲類型「指針CVT2」,結果是static_cast<cv T2*>(static_cast<cv void*>(v)) 如果兩個T1T2是標準佈局 類型(§3.9)和對準要求的T2不比 那些T1更嚴格,或者其中任何一種類型是void。 (...)

您還需要小心不要打破strict aliasing rules:通常,您不能使用兩個指針或對不同類型的引用相同內存位置的引用。