Reputation: 247
I have following code:
class Class
{
public:
std::string Read()
{
std::lock_guard<std::mutex> lock(mutex_);
return data_;
}
private:
std::mutex mutex_;
std::string data_;
};
What will be executed first - will a local copy (temporary) be created of the data_
string on the stack as a result of the function and then the lock will release the mutex, or will it be other way?
If so, does following line resolve the problem?
return std::string(data_);
Mutex is supposed to protect concurrent read/write of the data_
, so that those operations do not interfere.
Upvotes: 2
Views: 210
Reputation: 30604
The function returns the data_
as an rvalue, hence the result here will be calculated from the data_
member before the destructor of lock
is executed (as the function exits) and the mutex_
released.
return std::string(data_);
required? No.Upvotes: 5