I'm wondering what the standard says about the following piece of code. Can string
destructor of temporary object be executed before calling printPointer
?
p.s. VS2010 compiler doesn't complain about this code and works correctly.
void printPointer(const string* pointer)
{
cout << *pointer << endl;
}
const string* func(const string& s1)
{
return &s1;
}
int main()
{
printPointer(func("Hello, World!!!"));
}
Can
string
destructor of temporary object be executed before callingprintPointer
?
No, because temporary objects will be destroyed as the last step in evaluating the full-expression which contains the point where they were created, which means it will persist until the invoking of printPointer()
ends.
From the standard #12.2/4 Temporary objects [class.temporary]:
Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created.
And #12.2/6 Temporary objects [class.temporary]:
A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.