const_cast vs static_cast(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.
这篇关于const_cast 与 static_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const_cast 与 static_cast
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
