为什么我需要一个reinterpret_cast将Fred ** const转换为void ** const? [英] Why do I need a reinterpret_cast to convert Fred ** const to void ** const?
问题描述
我有一个指向 Fred
的指针的const指针,我不明白为什么 static_cast
isn足够。
I have a const pointer to a pointer to a Fred
and I don't understand why a static_cast
isn't sufficient.
typedef struct {
int n;
} Fred;
Fred *pFred;
Fred **const ppFred = &pFred;
void **const ppVoid = static_cast<void ** const>(ppFred);
请有人解释为什么 reinterpret_cast
需要将指向 Fred *
的指针转换为指向 void *
但 static_cast
可以将
Fred
的指针转换为指向 void
的指针。
Please could someone explain why a reinterpret_cast
is needed to convert a pointer to Fred*
to a pointer to void*
but static_cast
is fine to convert pointer to Fred
to a pointer to void
.
推荐答案
没有要求 Fred *
和 void * / code>具有相同的大小
和表示。 (我在他们没有的机器上工作,
虽然是在我的C ++日之前。)当你转换 Fred *
到
void *
,你会得到一个新的指针,可能有不同的大小和
表示,但没有关于对象大小和
表示的信息 void *
指向的。你知道它是
未知,并且使用这个 void *
的唯一方法是将它回复到
Fred *
(模数类似cv-qualifiers)。当您将 Fred **
转换为 void **
时,将指针转换为具体类型(指向 Fred *
的
指针)指向另一个具体类型的指针(指针
到 void *
)。因为不能保证这两个具体的
类型具有相同的大小和表示,所以转换需要
reinterpret_cast
。 void
是一个特殊的,非具体的类型,所以你可以
static_cast
并从指向 void
的指针。
void *
只是另一个具体的指针类型,所以转换和从
指针它遵循通常的规则(并且需要一个
reinterpret_cast
)。
There's no requirement that a Fred*
and a void*
have the same size
and representation. (I've worked on machines where they didn't,
although that was before my C++ days.) When you convert Fred*
to
void*
, you get a new pointer, with a possibly different size and
representation, but there is no information about the size and
representation of the object the void*
points to. You know that it is
unknown, and the only way to use this void*
is to cast it back to a
Fred*
(modulo things like cv-qualifiers). When you convert Fred**
to void**
, you're converting from a pointer to a concrete type (a
pointer to a Fred*
) to a pointer to another concrete type (a pointer
to a void*
). And since there's no guarantee that these two concrete
types have the same size and representation, the conversion requires a
reinterpret_cast
. void
is a special, non-concrete type, so you can
static_cast
a pointer to any type to and from a pointer to void
.
void*
is just another concrete pointer type, so casting to and from
pointers to it follows the usual rules (and requires a
reinterpret_cast
).
在许多方面,情况非常类似于 int
和
double
,其中
void *
起 int
(say)和 Fred *
角色 double
。
没有问题 static_cast
在 int
和之间
,但
在 int *
和之间强制转换
require reinterpret_cast
。
In many ways, the situation is very much like int
and double
, where
void*
plays the role of int
(say), and Fred*
the role of double
.
There's no problem static_cast
ing between int
and double
, but
casts between int*
and double*
require reinterpret_cast
.
这篇关于为什么我需要一个reinterpret_cast将Fred ** const转换为void ** const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!