【发布时间】:2013-04-25 20:47:11
【问题描述】:
给定这两个修改和返回字符串的函数:
// 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++,但我不明白为什么/如何。我担心第二个函数会调用自己,让我失去控制的递归,直到堆栈耗尽。这能保证有效吗?
【问题讨论】:
-
这很可能是尾递归。我不确定将 const-ref 调用转换为循环的语义,因此不要发布答案,而是查找尾递归,您会发现更多信息。
-
@peachykeen:不,这根本不是递归。
-
考虑选择一个更能突出问题的标题 - 例如“什么保证调用重载的非常量方法?”