const_cast 与 static_cast
将 const
添加到非常量对象中,哪种方法是首选?const_cast
或 static_cast
.在最近的一个问题中,有人提到他们更喜欢使用 static_cast
,但我原以为 const_cast
会使代码的意图更加清晰.那么使用 static_cast
使变量为 const 的参数是什么?
To add const
to a non-const object, which is the prefered method? const_cast<T>
or static_cast<T>
. In a recent question, someone mentioned that they prefer to use static_cast
, but I would have thought that const_cast
would make the intention of the code more clear. So what is the argument for using static_cast
to make a variable const?
推荐答案
不要使用.初始化引用对象的常量引用:
Don't use either. Initialize a const reference that refers to the object:
T x;
const T& xref(x);
x.f(); // calls non-const overload
xref.f(); // calls const overload
或者,使用 implicit_cast
函数模板,例如 Boost 中提供的:
Or, use an implicit_cast
function template, like the one provided in Boost:
T x;
x.f(); // calls non-const overload
implicit_cast<const T&>(x).f(); // calls const overload
考虑到 static_cast
和 const_cast
之间的选择,static_cast
绝对是可取的:const_cast
应该只用于抛弃 constness 因为它是唯一可以这样做的演员,而抛弃 constness 本质上是危险的.通过丢弃常量获得的指针或引用修改对象可能会导致未定义的行为.
Given the choice between static_cast
and const_cast
, static_cast
is definitely preferable: const_cast
should only be used to cast away constness because it is the only cast that can do so, and casting away constness is inherently dangerous. Modifying an object via a pointer or reference obtained by casting away constness may result in undefined behavior.
相关文章