brickner
brickner

Reputation: 6585

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.

Upvotes: 4

Views: 317

Answers (4)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361802

Is it safe to use the first version (with the const reference)?

Yes. Binding a temporary to a const reference lengthens the lifetime of the temporary to the lifetime of the reference itself, which is the scope in which the reference is declared:

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 has explained this in great detail in his article:

A Candidate For the “Most Important const”

It is worth reading. Must read it.

Upvotes: 2

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67237

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

Upvotes: 7

Xeo
Xeo

Reputation: 131907

A const-reference is allowed to bind to a temporary, and the live-time of the temporary will be extended to the live-time of the const-reference. So yes, it is safe to use.

Upvotes: 2

James Kanze
James Kanze

Reputation: 154047

It's safe in this simple case. It's easy to add code which makes it unsafe, however, and it's confusing to anyone who knows C++: why do you need a reference here? There's no reason to do so, and such code should generally be avoided.

Upvotes: 3

Related Questions