const
本文介绍了const_cast和static_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述要将 const 添加到非const对象,这是首选方法? const_cast< T> 或 static_cast< T> 。在最近的一个问题中,有人提到他们更愿意使用 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?
推荐答案p>不要使用。初始化一个引用对象的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 overloadxref.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 overloadimplicit_cast<const T&>(x).f(); // calls const overload给定 static_cast 和 const_cast , static_cast 是绝对优选的: const_cast 应该只用于丢弃 constness,因为它是唯一可以这样做的cast,并且抛弃constness本质上是危险的。通过指针或通过转换const const获得的引用修改对象可能导致未定义的行为。
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.
const