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
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
