是 const_cast吗?有没有用过?
最近我发现了一段C++代码,它有效地做了以下事情:
char* pointer = ...;
const char* constPointer = const_cast<const char*>( pointer );
显然作者认为const_cast的意思是“添加const”,但实际上const也可以添加隐式:
const char* constPointer = pointer;
是否有任何情况下我真的必须 const_cast
指向 const 的指针(const_cast
作为在上面的例子中)?
Recently I found a piece of C++ code that effectively does the following:
char* pointer = ...;
const char* constPointer = const_cast<const char*>( pointer );
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;
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当你有 2 个重载并且你想要强制执行 const 一个时。当您用一个术语称呼另一个术语时,通常会出现这种情况。
我有一个非常量 A 但想运行 get() const 我可能会强制转换。特别是我可能会在非常量本身的实现中这样做。
当然我们可以这样做:
所以我们不必进行强制转换,但这使得第一个解决方案成为单行解决方案,并且不需要创建临时变量。
Where you have 2 overloads and you want to force the const one to be executed. This is often the case when you call one in terms of the other.
I have a non-const A but want to run get() const I might cast. In particular I might do this in the implementation of the non-const itself.
Of course we could do:
so we did not have to cast but it makes the first solution a one-liner and no need to create a temp variable.
const_cast
尽管有其名称,但并不特定于const
;它与cv-qualifiers一起使用,它有效地包含const
和易失性
。虽然透明地允许添加这样的限定符,但删除任何限定符需要
const_cast
。因此,在您给出的示例中:
const_cast 的存在是虚假的(我个人认为它掩盖了语法)。
但是您可能希望删除
易失性
,在这种情况下您将需要它:例如,这可能会出现在驱动程序代码中。
const_cast
, despite its name, is not specific toconst
; it works with cv-qualifiers which effectively comprises bothconst
andvolatile
.While adding such a qualifier is allowed transparently, removing any requires a
const_cast
.Therefore, in the example you give:
the presence of the
const_cast
is spurious (I personally think it obscures the syntax).But you can wish to remove
volatile
, in which case you'll need it:This could appear, for example, in driver code.
也许在有 f(T*) 和 f(const T*) 的情况下强制重载解析。
Maybe to force overload resolution in cases where you have f(T*) and f(const T*).
您也可以使用
static_cast
来添加const。因此,我没有看到任何必须使用const_cast
来添加const
的情况。但是,当您想要更改对象的类型(例如为了重载解析)时,有时可能需要显式转换(无论是其中一种还是另一种)。例如
You can use
static_cast
to add const as well. So I don't see any situation where you have to useconst_cast
to addconst
. But explicit casting (be it one or another) can sometimes be needed when you want to change the type of the object for example for overload resolution.E.g.