Using const reference for return value

Take a 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 for this I need to write bar as follows:

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

Both versions seem to work, and I believe that with the same performance. Is it possible to use the first version (with reference to a constant)?

Thanks.

+4
source share
4 answers

Assigning a const temporary reference is absolutely valid. The temporary object will work until the link goes beyond the scope.

Although this does not make sense in your example, this function 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)); } 
+6
source

It is safe in this simple case. It's easy to add code that makes it unsafe, and it confuses anyone who knows C ++: why do you need a link here? There is no reason for this, and such code should usually be avoided.

+3
source

A reference to const can be tied to a temporary one, and the lifetime of a temporary one will be extended to the current time of a reference to const. So yes, it is safe to use.

+2
source

Is it possible to use the first version (with reference to a constant)?

Yes. Binding a temporary link to a constant extends the lifetime of the temporary resource of the link itself, which is the area in which this link 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 explained this in detail in his article:

Candidate for "Most Important Constant"

Worth to read. Must read it.

+2
source

All Articles