鉴于这些2个函数修改,并返回一个字符串:使用GCC G ++什么保证重载的非const方法被调用?
// 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?
}
此代码对我的作品,但我不明白为什么/如何。我担心第二个函数会自动调用,让我失控递归,直到堆栈耗尽。这是保证工作吗?
这是最有可能的尾递归。我不确定将const-ref调用转换为循环的语义,因此不会发布答案,而是查看尾递归,并且可以找到更多信息。 – ssube 2013-05-01 19:42:21
@peachykeen:不,它根本不是递归的。 – 2013-05-01 19:44:14
考虑选择一个更好地关注问题的标题 - 例如“什么保证重载的非const方法被调用?” – user2246674 2013-05-01 19:48:20