Mios
Mios

Reputation: 247

C++ - function end and local destruction order

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

Answers (1)

Niall
Niall

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.

  • Is a temporary (the return value) calculated before the mutex is released? Yes.
  • Is return std::string(data_); required? No.

Upvotes: 5

Related Questions