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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With