在不同类型之间转换 const 指针

casting const pointers between different types

我有一个 C++ 函数,其中一个输入参数的类型为 char const* buffer。我的理解是可以更改此数组的基础值,但不能移动指针本身以指向其他内容。

现在我要做的是将此数组重新解释为 unsigned short 并进行一些操作。所以,我会做类似的事情:

char const * current = &buffer[currentLine]; // Points to some location
unsigned short * const values = static_cast<unsigned short * const>(current);
// Change some of these values

这导致 invalid cast from top char * const to type short unsigned int * const

这个转换应该如何进行?

The way I understand it is that the underlying values of this array can be changed but the pointer itself cannot be moved to point to something else.

没有。这意味着您也不能更改此指针指向的实体,但您可以更改指针本身。要禁止更改指针,您必须使指针本身 const:

const char* const buffer;
            ^^^^^

How should this casting be performed?

转换应使用 reinterpret_cast

Only the following conversions can be done with reinterpret_cast, except when such conversions would cast away constness or volatility.

...

5) Any pointer to object of type T1 can be converted to pointer to object of another type cv T2.

所以你必须写:

unsigned short * const values = reinterpret_cast<unsigned short * const>(current);

甚至:

decltype(auto) values = reinterpret_cast<unsigned short * const>(current);

最后,static_cast在这里不适用,因为你试图在不同的不相关指针类型之间执行转换。

为了帮助您实现类型安全,每个转换都有一组有限的允许转换。这使您可以帮助传达您打算对转换执行的操作,如果您不小心执行了非预期的转换,编译器会警告您。

static_cast is a relatively safe casting operator. It allows the most common and safest conversions, including those that are already implicitly allowed. This does not include converting between unrelated pointers types, which is often dangerous. The correct cast operator to use is reinterpret_castreinterpret_cast 用于将某些内存解释为给定类型,而不管该内存实际表示的对象类型如何。除其他事项外,当您在不相关的指针类型之间进行转换时会用到它。

请记住,在给定选择时,总是首选使用最严格的转换运算符来执行您需要完成的工作。如果您犯了错误,这将使编译器有最多的机会通知您。

请注意,您正在指针类型之间进行转换。重要的是不要混淆两种类型之间的转换和两个指向这些类型的指针之间的转换。 charunsigned short 之间的转换方式与 pointercharpointer[= 之间的转换方式不同28=] 到 unsigned short.