In “The C++ Programming Language (3rd)” p.255:
A temporary can be used as an initializer for a const reference or a named object. For example:
void g(const string&, const string&); void h(string& s1, string& s2) { const string& s = s1+s2; string ss = s1+s2; g(s, ss); // we can use s and ss here }This is fine. The temporary is destroyed when “its” reference or named object go out of scope.
Is he saying that the temporary object created by s1+s2 is destroyed when ss goes out of scope?
Isn’t it get destroyed as soon as it is copy initialized to ss?
The only temporaries in your code are the
s1 + s2. The first one gets bound to the const-refs, and thus its lifetime is extended to that ofs. Nothing else in your code is a temporary. In particular, neithersnorssare temporaries, since they are manifestly named variables.The second
s1 + s2is of course also a temporary, but it dies at the end of the line, having been used to initializessonly.Update: Perhaps one point deserves emphasis: In the final line,
g(s, ss);, the point is thatsis a perfectly valid reference, and it is not a dangling reference as you might perhaps have expected, precisely because of the life-time extension rule for temporaries bound to const-references.