9

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

OopsUser
  • 4,642
  • 7
  • 46
  • 71

2 Answers2

11

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Thanks, Where can I find the standard ? Is it available for free ? – OopsUser Jun 06 '16 at 13:57
  • @OopsUser You might want to see [Where do I find the current C or C++ standard documents?](http://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents), or [The Definitive C++ Book Guide and List](http://stackoverflow.com/a/388282/3309790), basically, the [final draft before standardization](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf) is more than adequate (and free). – songyuanyao Jun 06 '16 at 13:59
-1

Destructors of local objects are called after 'the last line of your code'. Here is a relevant quote from Standard (3.7.3 / 3):

If a variable with automatic storage duration has initialization or a destructor with side effects, it shall not be destroyed before the end of its block, nor shall it be eliminated as an optimization even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 12.8

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • So will it happen before or after the copy constructor ? The copy constructor is not part of my code, the compiler handles it – OopsUser Jun 06 '16 at 13:52
  • OopsUser, the answer by @songyuanyao provides for even the better quote. After copy constructor, if it is called at all. – SergeyA Jun 06 '16 at 13:54