is const_cast< const Type *>有用吗?

is const_cast< const Type *>有用吗?

问题描述:

最近我发现了一个有效地执行以下操作的C ++代码:

Recently I found a piece of C++ code that effectively does the following:

char* pointer = ...;
const char* constPointer = const_cast<const char*>( pointer );

显然,作者认为 const_cast 添加const,但事实上 const 也可以隐式添加:

Obviously the author thought that const_cast means "add const", but in fact const can be just as well added implicitly:

const char* constPointer = pointer;

有什么情况下我真的需要 const_cast 指向const的指针( const_cast ,如上例)?

Is there any case when I would really have to const_cast to a pointer-to-const (const_cast<const Type*> as in above example)?

const_cast ,尽管其名称,但不特定于 const ;它使用 cv-qualifiers ,它有效地包括 const volatile

const_cast, despite its name, is not specific to const; it works with cv-qualifiers which effectively comprises both const and volatile.

添加这样的限定符是允许透明的,删除任何需要 const_cast

While adding such a qualifier is allowed transparently, removing any requires a const_cast.

因此,在此示例中,您提供:

Therefore, in the example you give:

char* p = /**/;
char const* q = const_cast<char const*>(p);

存在 const_cast

但你可以删除 volatile ,在这种情况下,需要它:

But you can wish to remove volatile, in which case you'll need it:

char const volatile* p = /**/;
char const* q = const_cast<char const*>(p);

这可能会出现在驱动程序代码中。

This could appear, for example, in driver code.