使用const引用值返回的值

| 看下面的例子:
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,但是我认为要做到这一点,我需要编写如下的bar:
void bar(int j) {
  string b = foo(j);
  cout << b;
}
两种版本似乎都可以使用,并且我相信它们具有相同的性能。 使用第一个版本(带有const引用)是否安全? 谢谢。     
已邀请:
将常量分配给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));
}
    
在这种简单情况下很安全。添加代码使其变得很不安全很容易,但是,这对任何了解C ++的人都感到困惑:为什么在这里需要引用?没有理由这样做,通常应避免使用此类代码。     
允许const引用绑定到临时引用,并且临时引用的生存时间将扩展为const引用的生存时间。因此,可以安全使用。     
  使用第一个版本(带有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)在他的文章中对此进行了详尽的解释: “最重要的常量”的候选人 值得一读。必须阅读。     

要回复问题请先登录注册