什么保证重载的非const方法被调用

What guarantees that the overloaded non-const method is invoked?

本文关键字:const 方法 调用 重载 什么      更新时间:2023-10-16

给定这两个修改和返回字符串的函数:

// modify the original string, and for convenience return a reference to it
std::string &modify( std::string &str )
{
    // ...do something here to modify the string...
    return str;
}
// make a copy of the string before modifying it
std::string modify( const std::string &str )
{
    std::string s( str );
    return modify( s ); // could this not call the "const" version again?
}

这段代码使用GCC g++为我工作,但我不明白为什么/如何。我担心第二个函数会调用自己,让我失去控制递归,直到堆栈耗尽。这能保证有效吗?

您有两个重载函数:

std::string &modify( std::string &str )
std::string modify( const std::string &str )

传递的是一个非const限定的std::string。因此,接受非const限定参数的函数更合适。如果不存在,编译器可以将非const限定字符串转换为const限定字符串以进行调用,但对于函数重载,不需要转换的调用比需要转换的调用更适合。

return modify( s ); // could this not call the "const" version again?

。它是而不是递归。它将调用参数为std::string &另一个重载。

这是因为表达式s的类型为std::string &,与另一个重载函数的参数类型相匹配。

为了递归,调用点的实参需要转换为std::string const &。但是在您的例子中,这种转换是不必要的,因为存在不需要转换的重载

这不是递归,而是重载。当你调用第二个函数时,它的参数是一个常量字符串。在这个函数内部,你调用另一个接受非const字符串的函数。你所做的是剥离字符串的const-ness,更好的方法是使用const_cast。

我将链接到另一个stackoverflow线程