2011-09-21 58 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:通常,您不能使用两个指针或对不同类型的引用相同内存位置的引用。