[英]Parameter passed by const reference returned by const reference
我正在阅读 C++ 常见问题解答第二版,常见问题解答编号 32.08。
常见问题解答说,由 const 引用传递并由 const 引用返回的参数可能会导致悬空引用。
但是如果参数通过引用传递并通过引用返回就可以了。
我知道在 const 引用的情况下它是不安全的,但是在参数是非 const 引用的情况下它是如何安全的。
FAQ的最后一行说“请注意,如果function通过非常量引用接受参数(例如,f(string&s)),则返回此引用参数的副本是安全的,因为临时不能通过非常量引用传递。”
需要对此有所了解!
如果你喜欢
const Foo & bar(const Foo &f) { return f; }
并称它为
const Foo &ret = bar(Foo());
这可以编译,但问题是现在 'ret' 是一个悬空引用,因为调用 Foo() 创建的临时 object 在 bar 返回后被释放。 这里详细的执行顺序是:
但是,如果您将 Foo 声明为
Foo & bar(Foo &f) { return f; }
那么您的呼叫 bar(Foo())将不会被编译器接受。 当您将临时 object 传递给 function 时,您只能通过 const 引用或作为副本获取; 这是语言定义的一部分。
临时对象可以通过 const 引用传递——当 function 返回临时对象被破坏时,调用者留下了一个悬空的引用。
例如:
#include <iostream>
using namespace std;
int const& output( int const& x)
{
cout << x << endl;
return x;
}
int main ()
{
int a = 1;
int const& ref1 = output( a); // OK
int const& ref2 = output(a+1); // bad
return 0;
}
我认为这个例子会有所帮助:
const int& f(const int& n)
{
return n;
}
int f1(int& n)
{
return n;
}
int main(int argc, char **argv)
{
//Passing a reference to an anonymous object created by
//the compiler to function f()
const int& n = f(10);
//Undefined behavior here as the scope of the anonymous object
//was only till previous statement
int k = n + 10;
//Compiler error - Can not pass non-const reference to a anonymous object
int n = f1(10);
}
这是一个关于 C++0x 右值引用的页面,开头是对左值和右值如何在 C++ 中工作的相当不错的总结,以及如何允许它们与引用绑定。
大多数关于 C++0x 中右值引用的文章都会让你对此有所了解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.