我正在学习 static_cast
和 reinterpret_cast
相关的知识。
如果我没记错的话,标准(9.2.18)说 reinterpret_cast
用于 pod 数据是安全的:
使用
reinterpret_cast
适当转换后的指向 POD-struct 对象的指针指向其初始成员(如果该成员是位域,则指向其中所在的单元),反之亦然。[注:因此,在 POD-struct 对象内可能存在未命名的填充,但不会出现在其开头,而是为了实现适当的对齐而必要。—end note]
我的问题是如何严格解释这个定义。 例如,仅布局兼容性是否足够? 如果不够,为什么?
对我来说,以下示例显示了一个严格的“仅限 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