gpt4 book ai didi

c++ - 为什么要在重载函数中使用 const_cast?

转载 作者:行者123 更新时间:2023-12-01 14:42:12 26 4
gpt4 key购买 nike

C++ Primer 一书的第 6.4 章陈述如下:

In § 4.11.3 (p. 163) we noted that const_casts are more useful in the context of overloaded functions. As one example, recall our shorterString function from § 6.3.2 (p. 224):

const string &shorterString(const string &s1, const string &s2)
{
return s1.size() <= s2.size() ? s1 : s2;
}

This function takes and returns references to const string. We can call the function on a pair of nonconst 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 nonconst 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);
}

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, nonconst arguments. Therefore, we know it is safe to cast that string back to a plain string& in the return.


我的问题:与下面的代码相比,这种方法有什么好处?性能不会因为函数调用而受到影响吗?或者这只是一个坏例子?
string &shorterString(string &s1, string &s2) {
return s1.size() <= s2.size() ? s1 : s2;
}

最佳答案

此示例具有误导性,因为在这种情况下,初始函数是如此简短和简单,与您提出的第二个完整定义相比,该方法几乎没有优势。
想法是你想要两个版本的函数,一个有 const 参数和返回,一个有引用参数和返回。这不是一个很好的例子,因为重载函数和初始函数一样长。
如果您假设初始 shorterString函数相当复杂,重载的函数仍然只需几行即可将引用参数转换为 const 并将返回 const 转换为引用。通过采用这种方法,您可以有两种不同的参数/返回行为,并且可以适本地重用,而不是重复代码。

关于c++ - 为什么要在重载函数中使用 const_cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63550467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com