c++ - const_cast 的合法用途是什么

标签 c++ constants

因为在 const_cast 的帮助下,任何人都可以修改我声明的常量对象 - const 限定符有什么用?

我的意思是,有人怎么能确保他声明的 const 无论如何都不会被修改?

最佳答案

您是对的,const_cast 的使用通常表示存在设计缺陷,或者 API 不受您的控制。

但是,有一个异常(exception),它在重载函数的上下文中很有用。我引用了 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 编写这个版本的函数:

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 string 的引用,我们 know 绑定(bind)到我们最初的非常量参数之一。因此,我们知道在返回中将该字符串转换回普通的 string& 是安全的。

关于c++ - const_cast 的合法用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18841952/

相关文章:

c++ - 不可变树的高效随机更新

c++ - C++ 的新操作是否可以保证地址返回的对齐?

C++如何使用经纬度确定时区

c++ - 不分配任何 char 内存的 const 字符串构造函数?

javascript - 正确使用 const 来定义函数

c++ - 将函数标记为 const 的非候选函数

c - OpenSSL 中的 const 难题

c# - 无法读取类实例中的常量?

c++ - 指向结构类型的指针如何表现?

c++ - 保存所有简单的计算或在每次需要结果时执行它们?