使用const引用返回值的值

时间:2011-05-24 08:08:10

标签: c++ reference return-value rvo nrvo

请看以下示例:

string foo(int i) {
  string a;
  ... Process i to build a ...
  return a;
}

void bar(int j) {
  const string& b = foo(j);
  cout << b;
}

我知道RVO和NRVO,但我认为为了做到这一点,我需要写下以下栏:

void bar(int j) {
  string b = foo(j);
  cout << b;
}

这两个版本似乎都有效,我相信具有相同的性能。 使用第一个版本(使用const引用)是否安全?

感谢。

4 个答案:

答案 0 :(得分:6)

将临时值分配给const引用是完全有效的。临时对象将一直存在,直到引用超出范围。

虽然在您的示例中没有意义,但此功能通常用于函数参数:

string foo(int i) {
    string a;
    // ...
    return a;
}

void bar(const string& str) {
    // ...
}

void buzz() {
    // We can safely call bar() with the temporary string returned by foo():
    bar(foo(42));
}

答案 1 :(得分:3)

在这个简单的案例中这是安全的。然而,添加使其不安全的代码很容易,并且对于了解C ++的人来说这很困惑:为什么在这里需要引用?没有理由这样做,通常应避免使用此类代码。

答案 2 :(得分:2)

允许const-reference绑定到临时表,临时表的实时时间将扩展到const-reference的实时时间。所以是的,使用它是安全的。

答案 3 :(得分:2)

  

使用第一个版本(使用const引用)是否安全?

是。将临时引用绑定到const引用会延长临时对生命周期的生命周期,这是引用引用的范围:

void f()
{
   const string& a = foo(10);

   //some work with a

   {
     const string& b = foo(20);

     //some work with b

   } //<----- b gets destroyed here, so the temporary also gets destroyed!

   //some more work with a

} //<----- a gets destroyed here, so the temporary associated 
                                  //with it also gets destroyed!

Herb Sutter在他的文章中详细解释了这一点:

A Candidate For the “Most Important const”

值得一读。必须阅读。