is const_cast< const Type *>有用吗? [英] Is const_cast<const Type*> ever useful?
问题描述
最近我发现了一个有效地执行以下操作的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.
这篇关于is const_cast< const Type *>有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!