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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也不要使用。初始化引用该对象的 const 引用:
或者使用
implicit_cast
函数模板,例如 Boost 中提供的:如果在
static_cast
和const_cast
之间进行选择,static_cast
为绝对更可取:const_cast
应该只用于抛弃常量,因为它是唯一可以做到这一点的强制转换,而抛弃常量本质上是危险的。通过放弃常量而获得的指针或引用修改对象可能会导致未定义的行为。Don't use either. Initialize a const reference that refers to the object:
Or, use an
implicit_cast
function template, like the one provided in Boost:Given the choice between
static_cast
andconst_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.我想说
static_cast
更好,因为它只允许您从非const
转换为const
(这是安全的),而不是朝另一个方向(不一定安全)。I'd say
static_cast
is preferable since it will only allow you to cast from non-const
toconst
(which is safe), and not in the other direction (which is not necessarily safe).这是 的一个很好的用例implicit_cast 函数模板。
This is a good use case for an implicit_cast function template.
您可以编写自己的演员表:
You could write your own cast: