const_cast的合法用途是什么 [英] What are Legitimate uses of const_cast

查看:60
本文介绍了const_cast的合法用途是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像在 const_cast 的帮助下,如果有人要修改我声明的常量对象,那么 const 限定词的用途是什么?

As with help of const_cast if some one is going to modify my declared constant object then what is use of const qualifier?

我的意思是说某人如何确保自己声明为 const 的内容不会被修改?

I mean how someone ensure that what he has declared as a const is not going to modified anyways??

推荐答案

您是正确的,使用 const_cast 经常表示存在设计缺陷或API无法控制.

You are right, uses of const_cast often indicates a design flaw, or an API that is out of your control.

但是,有一个例外,它在重载函数的上下文中很有用.我引用《 C ++ Primer》 一书中的一个例子:

However, there is an exception, it's useful in the context of overloaded functions. I'm quoting an example from the book C++ Primer:

// return a reference to the shorter of two strings
const string &shorterString(const string &s1, const string &s2)
{
    return s1.size() <= s2.size() ? s1 : s2;
}

此函数接受并返回对 const string 的引用.我们可以在一对非常量 string 参数上调用该函数,但会得到对 const string 的引用.我们可能希望有一个 shorterString 的版本,当给定非常量参数时,它将产生一个纯引用.我们可以使用 const_cast :

This function takes and returns references to const string. We can call the function on a pair of non-const string arguments, but we’ll get a reference to a const string as the result. We might want to have a version of shorterString that, when given non-const arguments, would yield a plain reference. We can write this version of our function using a const_cast:

string &shorterString(string &s1, string &s2)
{
    auto &r = shorterString(const_cast<const string&>(s1),
                            const_cast<const string&>(s2));
    return const_cast<string&>(r);
}

此版本通过将其参数强制转换为对 const 的引用来调用 shorterString 的const版本.该函数返回对 const字符串的引用,Know绑定到我们原始的非常量参数之一.因此,我们知道在返回中将该字符串强制转换回普通的 string& 是安全的.

This version calls the const version of shorterString by casting its arguments to references to const. That function returns a reference to a const string, which we know is bound to one of our original, non-const arguments. Therefore, we know it is safe to cast that string back to a plain string& in the return.

这篇关于const_cast的合法用途是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆