When is temporary use used as an initializer for a destroyed named object?

In "C ++ Programming Language (3rd)" p. 255:

Temporary can be used as an initializer to refer to a constant or a named object. For instance:

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 normal. Temporary is destroyed when "its" reference or named object goes out of scope.

Does he say that a temporary object created by s1+s2 is destroyed when ss goes out of scope? Won't it be destroyed as soon as it is copied to ss ?

+4
source share
2 answers

The only temporary ones in your code are s1 + s2 . The first is tied to const-ref s , and thus its lifetime increases to s . Nothing in your code is temporary. In particular, neither s nor ss are temporary, as they are explicitly called variables.

The second s1 + s2 , of course, is also temporary, but it dies at the end of the line, which was used only to initialize ss .

Update: perhaps one point deserves attention: in the final line g(s, ss); the point is that s is a legitimate link, and it’s not a chatty link, as you might expect, precisely because of the extended life rule for temporary links associated with const links.

+2
source

Both are true since two temporary files are created:

 //creates a temporary that has its lifetime extended by the const & const string& s = s1+s2; //creates a temporary that is copied into ss and destroyed string ss= s1+s2; 
+1
source

Source: https://habr.com/ru/post/1395938/


All Articles