Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the copy constructor for the return value happens

I have the following member function:

Person ClassB::DoSomethingAndReturnPerson()
{
 RAIIMutex myLock(&m_mutex);
 return m_person;
}

RAIIMutex is an helper class that recieves a mutex and locks it in the constructor and releases in the destructor.

m_person is of type Person (something very small in size). Other functions in other threads might change this member.

I want to return m_person by value (return a copy) and of course I want to avoid the situation where the m_person being changed in another thread while it's being copied in the return so I've added the lock.

But what happens first ? Does the compiler first creates a copy of m_person or first calls the destructor of myLock ?

Theoretically it easly solvable by doing something like this :

Person ClassB::DoSomethingAndReturnPerson()
{
 RAIIMutex myLock(&m_mutex);
 Person tmp = m_person;
 return tmp;
}

But I'm interested in knowing the answer to my question.

Thanks

like image 832
OopsUser Avatar asked Jun 06 '16 13:06

OopsUser


1 Answers

The copy-initialization of the returned value will be processed before.

From the standard, [stmt.return]/3 (emphasis mine)

The copy-initialization of the result of the call 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 ([stmt.jump]) of the block enclosing the return statement.

like image 187
songyuanyao Avatar answered Nov 07 '22 08:11

songyuanyao