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-ref s, and thus its lifetime is extended to that of s. Nothing else in your code is a temporary. In particular, neither s nor ss are temporaries, since they are manifestly named variables.

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

Update: Perhaps one point deserves emphasis: In the final line, g(s, ss);, the point is that s is 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.

其他提示

Both are true, because two temporaries 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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top