鑑於這些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