Nasser Al-Shawwa
Nasser Al-Shawwa

Reputation: 3653

In the absence of copy elision, is the copy/move constructor guaranteed to be called before the destructor?

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

Answers (1)

Kerrek SB
Kerrek SB

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

Related Questions