ant*_*_rh 2 c++ static-cast reinterpret-cast
鉴于以下条件:
struct A
{
int a;
};
struct B
{
int b;
};
int main()
{
A a {1};
A* p = &a;
Run Code Online (Sandbox Code Playgroud)
使用static_cast
和使用reinterpret_cast
via 进行铸造void*
会产生相同的结果吗?即以下表达式之间有什么区别吗?
static_cast <A*> ( static_cast <void*> (p) );
reinterpret_cast <A*> ( reinterpret_cast <void*> (p) );
Run Code Online (Sandbox Code Playgroud)
如果我们投指针到一个类的指针到其他课程,static_cast
并与reinterpret_cast
?这两个运营商之间有什么区别吗?下列表达式是否相同?
static_cast <B*> ( static_cast <void*> (p) );
reinterpret_cast <B*> ( reinterpret_cast <void*> (p) );
reinterpret_cast <B*> ( p );
Run Code Online (Sandbox Code Playgroud)
我可以B*
在此之后使用指针来访问b
成员吗?
下面的表达有什么区别吗?
Run Code Online (Sandbox Code Playgroud)static_cast <A*> ( static_cast <void*> (p) ); reinterpret_cast <A*> ( reinterpret_cast <void*> (p) );
不。
下列表达式是否相同?
Run Code Online (Sandbox Code Playgroud)static_cast <B*> ( static_cast <void*> (p) ); reinterpret_cast <B*> ( reinterpret_cast <void*> (p) ); reinterpret_cast <B*> ( p );
是的。
理解这一点的简单方法是考虑如何指定从指针到指针的 reinterpret_cast。reinterpret_cast<T*>(ptr)
指定的行为与static_cast<T*>(static_cast<void*>(ptr))
(为了简单起见,我省略了 cv 限定符)完全相同。
当然,static_cast<T>(static_cast<T>(anything))
等价于static_cast<T>(anything)
因为外部强制转换始终是身份转换。
我可以在此之后使用 B* 指针访问 b 成员吗?
不。如果你这样做了,那么程序的行为将是未定义的。
归档时间: |
|
查看次数: |
142 次 |
最近记录: |