我正在尝试了解static_cast
和reinterpret_cast
。
如果我是正确的,标准(9.2.18)说reinterpret_cast
对于 pod 数据是安全的:
一个指向 POD 结构对象的指针,使用 a 进行适当转换
reinterpret_cast
,指向它的初始成员(或者如果该成员是位字段,则指向它所在的单元),反之亦然。[注意:因此,在 POD 结构对象中可能存在未命名的填充,但不是在其开头,这是实现适当对齐所必需的。——尾注]
我的问题是如何严格解释这一点。例如,布局兼容性是否足够?如果没有,为什么不呢?
对我来说,以下示例显示了一个示例,其中严格的“仅 POD 有效”解释似乎是错误的。
class complex_base // a POD-class (I believe)
{
public:
double m_data[2];
};
class complex : public complex_base
{ //Not a POD-class (due to constructor and inheritance)
public:
complex(const double real, const double imag);
}
double* d = new double[4];
//I believe the following are valid because complex_base is POD
complex_base& cb1 = reinterpret_cast<complex_base&>(d[0]);
complex_base& cb2 = reinterpret_cast<complex_base&>(d[2]);
//Does the following complete a valid cast to complex even though complex is NOT POD?
complex& c1 = static_cast<complex&>(cb1);
complex& c2 = static_cast<complex&>(cb2);
complex_base::m_data
此外,如果受到保护(这意味着complex_base
不是 pod),可能会破坏什么?[编辑:以及如何保护自己/检测此类破损]
在我看来,布局兼容性应该足够了——但这似乎不是标准所说的。
编辑:感谢您的回答。他们还帮我找到了这个, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2342.htm