Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which will be executed first, RAII or function return value

MyClass has a member function that needs to return its' member variable, and the function must be thread safe, so I use a mutex to protect the data.

I have two implementation as below:

version 1:

string MyClass::name() {
    m_mutex.lock();
    string temp = m_name;
    m_mutex.unlock();
    return temp;
}

version 2:

string MyClass::name() {
    MutexLocker lock(mutex);
    return m_name;
}

I known that version 1 has no problem, but I need to type more code.

The problem is, I'm not sure whether version 2 is correct or not. Will the mutex lock will be released before the thread access m_name?

like image 693
tomnotcat Avatar asked Nov 24 '13 07:11

tomnotcat


1 Answers

The version 2 is correct as well (in fact, that is better than the first version!).

The value is copied first before mutex is released through the destructor of the local object. The opposite is not possible because the local object gets destroyed when it goes out of scope, but you must note that the return statement must be executed in the scope, so it must happen before destruction. Conversely, the return statement cannot be executed after the local object goes out of scope.

From call-stack point of view, the local objects are destroyed when the stack starts unwinding, but the function including the return statement is executed long before stack-unwinding. That ensures m_name is copied much before the releasing the mutex.

Or think of this simple code:

std::string f()
{
    std::string s = "Nawaz";
    return s; //Think of this line!
}

Is s copied1after its destruction? Is that even possible? Wouldn't it make programming in C++ impossible if s is copied after its destruction?

1. Or better say, moved. :-)

like image 190
Nawaz Avatar answered Sep 19 '22 16:09

Nawaz