Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

c++ - How to use lock_guard when returning protected data

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?

Example:

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...