如何在返回受保护的数据时使用lock_guard [英] How to use lock_guard when returning protected data

查看:103
本文介绍了如何在返回受保护的数据时使用lock_guard的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用 boost :: lock_guard (或类似的范围锁)和使用应该由锁保护的变量在 return 语句。

I have a question concerning the use of boost::lock_guard (or similar scoped locks) and using variables that should be protected by the lock in a return statement.

如何破坏本地对象和复制返回值?如何对返回值进行优化?

How is the order of destroying local objects and copying the return value? How does return value optimization affect this?

示例:

Data Class::GetData()
{
    boost::lock_guard<boost::mutex> lock(this->mMutex);
    return this->mData;
}

这是正确的(如果mData是受mMutex保护的变量)?或者我将使用一个局部作用域和一个临时的,如下面的例子所示:

Would this be correct (if mData is the variable protected by mMutex)? Or would I have to use a local scope and a temporary like shown in the example below:

Data Class::GetData()
{
    Data ret;
    {
        boost::lock_guard<boost::mutex> lock(this->mMutex);
        ret = this->mData;
    }
    return ret;
}


推荐答案

你的第一个例子是正确的。返回值是在局部变量被销毁之前,因此在释放锁之前构建的。

Just a straight return as in your first example is correct. The return value is constructed before the local variables are destroyed, and thus before the lock is released.

这篇关于如何在返回受保护的数据时使用lock_guard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆