Returning a member by value from a mutex-locked function

Viewed 348

Suppose (for a toy example) that I have the class:

class Foo {
    mutable std::mutex mutex;
    std::vector<int> data;
public:
    void add(int x) {
        std::lock_guard<std::mutex> lock(mutex);
        data.push_back(x);
    }
    std::vector<int> getData() const;
};

Now, I'm sure this is an OK version of getData():

std::vector<int> Foo::getData() const {
    std::lock_guard<std::mutex> lock(mutex);
    auto result = data; // Safely copy.
    return result; // Return a local by value.
} // lock goes out of scope and unlocks.

but what about this? Is this safe?:

std::vector<int> Foo::getData() const {
    std::lock_guard<std::mutex> lock(mutex);
    return data; // <- Is this threadsafe?
}

The return line happens within the lock's lifetime, so maybe it's safe? OTOH, we are copying a member, so data outlives lock. Maybe the lock goes out of scope before data is copied to the caller?

So: Is the second version threadsafe?

0 Answers
Related