Search code examples
c++referencereturn-valuervonrvo

Using a const reference to a returned by value value


Look at the following example:

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

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

I know RVO and NRVO, but I thought that in order to do that, I need to write bar as the following:

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

Both versions seem to work, and I believe with the same performance. Is it safe to use the first version (with the const reference)?

Thanks.


Solution

  • Assigning a temporary to a const reference is perfectly valid. The temporary object will live until the reference goes out of scope.

    While it does not make sense in your example, this feature is often used for function arguments:

    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));
    }