Ale*_*Dan 5 c++ reference temporary
例如,这个函数f定义如下:
int f(int x){return x;}
Run Code Online (Sandbox Code Playgroud)
如你所知你不能分配对这个临时int的引用:
int& rf=f(2);// this will give an error
Run Code Online (Sandbox Code Playgroud)
但如果我重新定义我的函数f如下:
int& f(int x){return x;}
f(2);// so now f(2) is a reference of x, which has been destroyed
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:编译器怎么能不让你创建一个临时的引用,这个引用将在statment之后被销毁(在第一种情况下为int).另一方面,它允许你创建一个引用f(2),x而编译器知道这个将被销毁之后return.
返回对本地的引用是编译器难以或不可能检测到的.例如:
int & f()
{
int x;
extern int & g(int & x);
// Does this return a reference to "x"?
// The compiler has no way to tell.
return g(x);
}
Run Code Online (Sandbox Code Playgroud)
即使不调用外部函数,仍然很难分析复杂的程序流以判断返回的引用是否是本地的; 而不是试图定义什么算"足够简单"来诊断,标准不需要诊断 - 它只是声明它给出了未定义的行为.一个好的编译器应该发出警告,至少在简单的情况下.
将临时引用绑定到非const引用是编译器可以轻松检测的内容,因此标准需要对其进行诊断.