问题描述
我对 reinterpret_cast
与 static_cast
的适用性有点困惑.从我读到的一般规则是,当类型可以在编译时解释时使用静态转换,因此使用 static
这个词.这也是 C++ 编译器在内部用于隐式转换的转换.
I am little confused with the applicability of reinterpret_cast
vs static_cast
. From what I have read the general rules are to use static cast when the types can be interpreted at compile time hence the word static
. This is the cast the C++ compiler uses internally for implicit casts also.
reinterpret_cast
s 适用于两种场景:
- 将整数类型转换为指针类型,反之亦然
- 将一种指针类型转换为另一种.我得到的一般想法是这是不可移植的,应该避免.
我有点困惑的地方是我需要的一种用法,我从 C 调用 C++,C 代码需要保留 C++ 对象,所以基本上它包含一个 void*
.void *
和 Class 类型之间应该使用什么类型转换?
Where I am a little confused is one usage which I need, I am calling C++ from C and the C code needs to hold on to the C++ object so basically it holds a void*
. What cast should be used to convert between the void *
and the Class type?
我见过 static_cast
和 reinterpret_cast
的用法?虽然从我一直在阅读的内容看来 static
更好,因为转换可以在编译时发生?虽然它说使用 reinterpret_cast
从一种指针类型转换为另一种?
I have seen usage of both static_cast
and reinterpret_cast
? Though from what I have been reading it appears static
is better as the cast can happen at compile time? Though it says to use reinterpret_cast
to convert from one pointer type to another?
推荐答案
C++ 标准保证以下内容:
The C++ standard guarantees the following:
static_cast
指向和来自 void*
的指针会保留地址.即,下面的a
、b
和c
都指向同一个地址:
static_cast
ing a pointer to and from void*
preserves the address. That is, in the following, a
, b
and c
all point to the same address:
int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);
reinterpret_cast
仅保证如果您将指针转换为不同的类型,然后 reinterpret_cast
将其恢复为原始类型,您会得到原始值.所以在下面:
reinterpret_cast
only guarantees that if you cast a pointer to a different type, and then reinterpret_cast
it back to the original type, you get the original value. So in the following:
int* a = new int();
void* b = reinterpret_cast<void*>(a);
int* c = reinterpret_cast<int*>(b);
a
和 c
包含相同的值,但 b
的值未指定.(在实践中,它通常包含与 a
和 c
相同的地址,但这在标准中没有指定,在具有更复杂内存系统的机器上可能不是这样.)
a
and c
contain the same value, but the value of b
is unspecified. (in practice it will typically contain the same address as a
and c
, but that's not specified in the standard, and it may not be true on machines with more complex memory systems.)
对于与 void*
之间的转换,应该首选 static_cast
.
For casting to and from void*
, static_cast
should be preferred.
这篇关于何时使用 reinterpret_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!