2 ms·
I do not think they had this kind of usage in mind when they allowed it and i think the use case for it is in using a const reference to a function argument.Mos
by mhogomchungu 13y ago
I do not think they had this kind of usage in mind when they allowed it and i think the use case for it is in using a const reference to a function argument.Most people use this all the time without thinking about it or wondering what is the origin of the variable they are accessing through the const reference.
eg is when you have a function like below:
void foo( const string& str )
{
cout << str ;
}
The above function takes a const reference to string and uses it without caring if the passed in variable is a temporary variable or not.
Now declare a function as:
string bar() { return "abc" ; }
and the above two function can be used with:
foo( bar() ) ;
I think this use case is the one that allowed the use of temporary variable from a const reference and people do this all the time.
- MaulingMonkey 13y ago> I do not think they had this kind of usage in mind when they allowed it I think they did based on 8.5.3 which has this example: struct A { }; struct B : public A { } b; extern B f(); const A& rca = f(); // Either bound to the A sub-object of the B rvalue, // or the entire B object is copied and the reference // is bound to the A sub-object of the copy As well as 12.2 para 5: class C { // ... public: C(); C(int); friend C operator+(const C&, const C&); ˜C(); }; C obj1; const C& cr = C(16)+C(23); C obj2; In the C++ standard which talks about the temporary bound to cr existing for the duration of the entire program? Moreover, why would a rule for const references be specifically needed to handle foo( bar() );, but no equivalent rule for bar().foo(); which handles an implicit non-const pointer?
- Jare 13y agoI believe it was explicitly defined to support this use case, since the extra lifetime it is added on top of the regular "temporary lasts until the end of the full expression in which it is created". The "full expression" clause would be sufficient for function parameters, because the expression is not finished until the entire expression has been evaluated, and this includes executing and returning from the function that received the temporary. In an indirect way though I agree: it is important for the language to make it easy to break apart complex expressions, but without this lifetime extension, I suspect it may not be possible to un-nest function calls without creating more copies (RVO may prove me wrong though - not studied the case in full).