简体   繁体   中英

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 ?

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 copied 1 after 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 . :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM