8

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!!!"));
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
skap
  • 320
  • 3
  • 16
  • 4
    The temporary string is only destructed at the end of the statement. Someone can probably dig up the reference (something with sequence points?) but you can see it yourself: http://ideone.com/N3Brll – CompuChip Jul 13 '16 at 07:52

1 Answers1

8

Can string destructor of temporary object be executed before calling printPointer?

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.

explanatory demo

songyuanyao
  • 169,198
  • 16
  • 310
  • 405