在带有static_cast的const-cast和"this"的const_cast之间添加C-ness的C ++区别.目的? [英] C++ difference between adding const-ness with static_cast and const_cast of "this" object?
问题描述
按照Scott Meyers的说法,为防止getter的const版本和getter的非const版本中的代码重复出现,请从非const版本中调用方法的const版本: static_cast< constA&>(* this).Methodology();
然而,由于我输入的Visual Assist X Intellisense过于狂热,导致意外使用: const_cast< const A&>(* this).Methodology();
正常运行.
As per Scott Meyers, to prevent repetition of code in the const version of a getter and the non-const version of a getter, call the const version of the method from the non-const version: static_cast<const A&>(*this).Methodology();
however, in accidental usage due to an overzealous Visual Assist X Intellisense I typed: const_cast<const A&>(*this).Methodology();
and it worked just fine.
在这种情况下,使用特定演员表有什么区别?
What are any and all differences in this case with using a particular cast?
正在使用的IDE:Visual Studio 2010.
IDE in use: Visual Studio 2010.
推荐答案
假定 this
的类型为 A *
,没有区别.
Assuming that the type of this
is A*
, there is no difference.
通常 const_cast
可以丢弃 const
说明符(从任何级别的间接寻址或模板参数开始)
In general const_cast
can cast aways the const
specifier (from any level of indirection or template parameter)
static_cast<>
可以将一种类型转换为另一种类型.
static_cast<>
can cast a type to another if the target type is in the source's type hierarchy.
他们不能做彼此的工作.
They cannot do each other's work.
它们在您的情况下都起作用的原因是因为您引入了 const-ness,而不是将其删除(从函数的非const版本中调用此
是 A *
,没有const).你也可以写
The reason they both worked in your case is because you have introduced const-ness, as opposed to having taken it away (calling from the non-const version of the function the type of this
is A*
, no const). You could just as well have written
const A& tmp = *this;
tmp.Methodology();
,它不需要任何转换就可以工作.强制转换是为了方便和简洁而不必引入新变量.
and it would have worked without the need for any casting. The casting is used for convenience and terseness to not have to introduce a new variable.
注意:知道要转换为正确的类型时,您可以在此处使用 static_cast<>
.在其他情况下(不确定时),您需要使用 dynamic_cast<>
进行运行时类型检查以确保转换有效
Note: you can use static_cast<>
here as you know that you are casting to the right type. In other cases (when you cannot be sure) you need to use dynamic_cast<>
that does a runtime type check to ensure the conversion is valid
这篇关于在带有static_cast的const-cast和"this"的const_cast之间添加C-ness的C ++区别.目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!