简体   繁体   English

哪个将首先执行,RAII或函数返回值

[英]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. MyClass有一个成员函数,需要返回它的'成员变量,并且该函数必须是线程安全的,所以我使用互斥锁来保护数据。

I have two implementation as below: 我有两个实现如下:

version 1: 版本1:

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

version 2: 版本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. 我知道版本1没有问题,但我需要输入更多代码。

The problem is, I'm not sure whether version 2 is correct or not. 问题是,我不确定版本2是否正确。 Will the mutex lock will be released before the thread access m_name ? 在线程访问m_name之前是否会释放互斥锁?

The version 2 is correct as well (in fact, that is better than the first version!). 版本2也是正确的(事实上,这比第一版更好 !)。

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. 相反的情况是不可能的,因为本地对象在超出范围时会被销毁,但是您必须注意必须在范围内执行return语句,因此它必须在销毁之前发生。 Conversely, the return statement cannot be executed after the local object goes out of scope. 相反,在本地对象超出范围后,无法执行return语句。

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. 从调用堆栈的角度来看,当堆栈开始展开时会破坏本地对象,但是在堆栈展开之前很久就会执行包含return语句的函数。 That ensures m_name is copied much before the releasing the mutex. 这确保在释放互斥锁之前复制m_name

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? s其销毁复制1? Is that even possible? 这甚至可能吗? Wouldn't it make programming in C++ impossible if s is copied after its destruction? 如果销毁之后复制s是不是不能用C ++编程?

1. Or better say, moved . 或者更好的说, 感动 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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