In C++ you can bind return value of a function (which return value, not reference) to const reference and code will still be valid because lifetime of this temporary will be prolonged till the end of scope. For example
std::string get_string() {
return "abc";
}
void f() {
const std::string& str = get_string();
std::cout << str; // valid, str is not dangling reference.
}
My question is, when is it useful, e.g. when is code like
A get_a();
const A& a = get_a();
better than the code
A get_a();
A a = get_a();
and in what way (e.g. faster, smaller binary size, etc)? What should be the implementations of A
, get_a
and code after calling get_a
?
I've tested several cases by hand and in each case it seems to have the same number of copies and moves.
Let's restrict this question to current C++ standard, modern versions of compilers and builds with optimisation enabled (O2, O3 or equivalents for other compilers)
auto &&
can bind to anything and so is more adaptable but that's not the same thing. But perhaps I misunderstand or perhaps I'm just picking nits. Learnt some interesting stuff aboutauto &&
here. – Zadazadack