sha*_*oth 8 c++ casting static-cast reinterpret-cast
有一组关于交叉演员的问题(演员从T1*无关到演员T2*),例如这个和这个.答案通常是这样的:reinterpret_cast实现定义和void*后面的转换static_cast是明确定义的.然而,我没有看到任何reinterpret_cast使用时可能出现问题的真实例子.
什么是真实的例子,其中铸造void*工作,而reinterpret_cast不是?
现实生活中的例子,其中通过 void* 进行转换有效,而 reinterpret_cast 无效
如果我将这句话解释为,强制转换void*可以帮助我避免未定义的行为,但reinterpret_cast不会,那么下面是一个示例。
reinterpret_cast<TYPE*&>(指针引用)可能会违反严格的别名规则(至少在 g++ 中会发生)并导致未定义的行为。演示。
但是,这static_cast<void*&>将导致编译器错误并避免您出现此类未定义的行为。演示。
我在智能指针中看到过这样的用法:
template<class TYPE>
struct SmartPointer
{
void *p;
TYPE& operator ++ ()
{
(reinterpret_cast<TYPE*&>(p))++; // breaking strict aliasing rule
return *this;
}
}
Run Code Online (Sandbox Code Playgroud)