Implicit destructor execution on function call

I am wondering what the standard says about the following code snippet. Is it possible to execute a string destructor of a temporary object before calling printPointer ?

ps The VS2010 compiler does not 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!!!")); } 
+8
c ++ language-lawyer destructor temporary object-lifetime
source share
2 answers

Can a string destructor of a temporary object execute before calling printPointer ?

No, since temporary objects will be destroyed as the last step in evaluating the full expression that contains the point at which they were created, which means that it will remain until the printPointer() call completes.

From standard # 12.2 / 4 Temporary objects [Class.temporary] :

Temporary objects are destroyed as the last step in evaluating the full expression ([intro.execution]), which (lexically) contains the point at which 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]) is stored until the completion of the full expression containing the call.

explanatory demonstration

+9
source share

Your line will not be destroyed until the end of the program, since s1 is a reference to it (which means that it is not destroyed in func ). There is no pass-by-value or return-by-value in func . There are no problems with this code.

-6
source share

All Articles