引用返回值时出错

error on reference to return value

本文关键字:出错 返回值 引用      更新时间:2023-10-16

此代码无法通过编译。唯一的区别是返回类型。Foo1 的返回类型是用户定义的结构体,Foo2 的返回类型是 int。

struct test
{    
};    
test Foo1()  
{  
    return test();  
}  
int Foo2()  
{  
    return 0;  
}  
int main()  
{  
    test& r1 = Foo1(); //ok  
    int& r2 = Foo2(); //no but why? Is it the C++ standard way?  
    return 0;  
}

它要么是编译器错误,要么是它的"语言扩展"(例如MS VC++有许多这样的"语言扩展")。在函数调用的两种情况下,编译器都会发出错误,因为它可能不会将临时对象绑定到非 const 引用。

如果你想有一个引用,你仍然可以使用对 const 的引用,否则两行都不会编译:

struct test
{
};
test Foo1()
{
    return test();
}
int Foo2()
{
    return 0;
}
int main()
{
    const test& r1 = Foo1(); // ok now
    const int& r2 = Foo2();  //ok now
    return 0;
}