Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
brickner Avatar asked Dec 09 '22 08:12

brickner


1 Answers

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));
}
like image 69
Ferdinand Beyer Avatar answered Dec 26 '22 00:12

Ferdinand Beyer