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
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
