Reputation: 3653
Pretty much what the title says. Consider this example:
MyClass func()
{
MyClass myInstance;
return myInstance;
}
int main()
{
auto myInstance = func();
}
In the absence of copy elision, is the copy or move constructor of MyClass
guaranteed to be called before the destructor as the call to func()
returns myInstance
? I imagine a class like std::shared_ptr
would make use of such a property when returned by value.
Also, are there any pitfalls to relying on this behaviour?
Upvotes: 1
Views: 50
Reputation: 476940
Yes.
From [stmt.return]/3:
The copy-initialization of the returned entity is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables (6.6) of the block enclosing the return statement.
Upvotes: 4