说我想投A*
to char*
反之亦然,我们有两种选择(我的意思是,我们很多人认为我们有两种选择,because两者似乎都有效!因此造成混乱!):
struct A
{
int age;
char name[128];
};
A a;
char *buffer = static_cast<char*>(static_cast<void*>(&a)); //choice 1
char *buffer = reinterpret_cast<char*>(&a); //choice 2
两者都工作正常。
//convert back
A *pA = static_cast<A*>(static_cast<void*>(buffer)); //choice 1
A *pA = reinterpret_cast<A*>(buffer); //choice 2
即使这样也能正常工作!
那么为什么我们有reinterpret_cast
在 C++ 中,当两个链子 static_cast
能做好它的工作吗?
有些人可能认为这个主题与前面的主题重复,例如本文底部列出的主题,但事实并非如此。这些话题仅在理论上讨论,但他们都没有给出哪怕一个例子来证明 why reintepret_cast
确实需要,并且two static_cast
would surely失败。我同意,一个 static_cast 会失败。但两个怎么样?
如果两个链接的语法static_cast
看起来很麻烦,那么我们可以写一个函数模板,让它对程序员更友好:
template<class To, class From>
To any_cast(From v)
{
return static_cast<To>(static_cast<void*>(v));
}
然后我们可以使用它,如下所示:
char *buffer = any_cast<char*>(&a); //choice 1
char *buffer = reinterpret_cast<char*>(&a); //choice 2
//convert back
A *pA = any_cast<A*>(buffer); //choice 1
A *pA = reinterpret_cast<A*>(buffer); //choice 2
另外,请参阅这种情况any_cast
可能有用:fstream 读写成员函数的正确转换 https://stackoverflow.com/questions/4672991/proper-casting-for-fstream-read-and-write-member-functions/4673042.
所以我的问题基本上是,
- 为什么我们有
reinterpret_cast
in C++?
- 请给我展示一个例子两个链子
static_cast
肯定无法完成同样的工作吗?
- 使用哪种演员阵容; static_cast 还是reinterpret_cast? https://stackoverflow.com/questions/4476182/which-cast-to-use-static-cast-or-reinterpret-cast
- 从 Void* 转换为 TYPE* :static_cast 或 reinterpret_cast https://stackoverflow.com/questions/3064509/cast-from-void-to-type-using-c-style-cast-static-cast-or-reinterpret-cast