C++ nonconst-const引用函数重载

use*_*710 5 c++ g++ pass-by-reference rvalue lvalue

在以下代码中:

int foo(const int& f) //version 1
{
    int g = f;
    return int(foo(g)); // calls itself, turning into SO
}

int& foo(int& f) //version 2
{
    f *= -1;
    return f;
}

int main()
{
    int f = 11;
    cout << foo(f) << endl;
    cout << foo(22) << endl;
}
Run Code Online (Sandbox Code Playgroud)

第一个cout按预期打印-11; f是一个左值,所以它绑定到foo的第二个版本(虽然它也可以绑定到第一个版本,第二个版本它是一个更好的匹配).

第二个调用foo是使用rvalue作为参数,因此唯一可行的版本foo是第一个.到现在为止还挺好.在第一个版本中foo,我制作了参数的副本,因此我可以调用第二个版本(带左值)并在调用第二个版本之后返回它的副本foo.事情是这会变成堆栈溢出; 仍然foo会调用第一个版本.

有人可以向我解释为什么会这样吗?我希望g在第一个版本中foo绑定到foo作为参数传递的第二个版本.

Luc*_*ore 10

这很简单 - foo在这一点上只是意味着foo(const int& f).没有第二选择.还没.切换定义.或者将它们分开:

int foo(const int& f);
int& foo(int& f);

int main()
{
    int f = 11;
    cout << foo(f) << endl;
    cout << foo(22) << endl;
}


int foo(const int& f) //version 1
{
    int g = f;
    return int(foo(g)); // calls itself, turning into SO
}

int& foo(int& f) //version 2
{
    f *= -1;
    return f;
}
Run Code Online (Sandbox Code Playgroud)