C++ 什么可以保证调用重载的非常量方法?
给定以下两个修改并返回字符串的函数:C++ 什么可以保证调用重载的非常量方法?,c++,recursion,signature,C++,Recursion,Signature,给定以下两个修改并返回字符串的函数: // 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 befor
// 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?
}
这段代码适用于我使用GCCG++,但我不明白为什么/如何。我担心第二个函数会自动调用,在堆栈耗尽之前,我将无法控制递归。这保证有效吗
return modify( s ); // could this not call the "const" version again?
不。它是而不是递归。它将调用另一个重载,其参数为std::string&
这是因为表达式s
的类型是std::string&
,它与另一个重载函数的参数类型匹配
为了递归,调用站点的参数需要转换为
std::string const&
。但在您的情况下,这种转换是不必要的,因为存在不需要转换的重载。您有两个重载函数:
std::string &modify( std::string &str )
std::string modify( const std::string &str )
您传递的是一个非常量限定的
std::string
。因此,采用非常量限定参数的函数更适合。如果不存在,编译器可以将非常量限定字符串转换为常量限定字符串以进行调用,但是对于函数重载,不需要转换的调用比需要转换的调用更合适。这不是递归,而是重载。调用第二个函数时,进入该函数的参数是一个常量字符串。在该函数中,调用另一个接受非常量字符串的函数。您正在做的是剥离字符串的常量,更好的方法是使用const_cast
这很可能是尾部递归。我不确定把一个const REF调用转换成一个循环,所以不要张贴答案,而是查找尾部递归,你会发现更多的信息。@ PeajyHyn:不,它根本不是递归。考虑选择一个更好地关注问题的标题——例如“什么保证了重载的非const方法被调用?”我不想除掉康斯特内斯。这将导致一个看似常量的字符串被修改!您可以做的是通过如下操作分配非常量字符串:std::string&str2=const_cast(str)。str将保持不变,但您可以随意修改str2。