Victor said:
Not at all. I mean, I don't think I cleared it up. But that
muddying of the waters wasn't intentional. I myself am in the
fog WRT this. One thing I know for sure, it's not a local
object.
Based on TC++PL "10.4.10 Temporary Objects" I think the temporary
created after the return of the literal is destroyed at the end of the
expression.
An example mentioned there:
"However, in combination they can cause obscure problems.
For example:
void f(string& s1, string& s2, string& s3)
{
const char* cs= (s1+s2).c_ str() ;
cout << cs;
if (strlen(cs=(s2+s3).c_ str())<8 && cs[0]==´a´) {
// cs used here
}
}
Probably, your first reaction is "but don’t do that," and I agree.
However, such code does get written, so it is worth knowing how it is
interpreted.
A temporary object of class string is created to hold s1+s2. Next, a
pointer to a C-style string is extracted from that object. Then – at the
end of the expression – the temporary object is deleted.
Now, where was the C-style string allocated? Probably as part of the
temporary object holding s1+s2, and that storage is not guaranteed to
exist after that temporary is destroyed. Consequently, cs points to
deallocated storage. The output operation cout<<cs might work as
expected, but that would be sheer luck. A compiler can detect and warn
against many variants of this problem.
The example with the if-statement is a bit more subtle. The condition
will work as expected because the full expression in which the temporary
holding s2+s3 is created is the condition itself.
However, that temporary is destroyed before the controlled statement is
entered, so any use of cs there is not guaranteed to work.
Please note that in this case, as in many others, the problems with
temporaries arose from using a high-level data type in a low-level
way. A cleaner programming style would have not only yielded a more
understandable program fragment, but also avoided the problems with
temporaries completely. For example:
...."