Which will be executed first, RAII or function return value

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

I have two implementations as shown 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 knew that version 1 had no problems, but I needed to enter more code.

The problem is that I'm not sure if version 2 is correct or not. Will a mutex lock be released before thread access m_name?

+4
source share
1 answer

Version 2 is also correct (in fact, it is better than the first version!).

, mutex . , , , , return , . , return .

-, , , , return, . , m_name .

:

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

s 1 ? ? ++ , s ?

1. , .: -)

+13

All Articles