Question

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.

Was it helpful?

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

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top