Suppose we have a class
with a std::mutex
:
class Foo
{
std::mutex mutex_;
std::string str_;
// other members etc
public:
friend void swap(Foo& lhs, Foo& rhs) noexcept;
}
What is the appropriate way to implement the swap
method here? Is it required/safe to lock each mutex separately and then swap everything? e.g.
void swap(Foo& lhs, Foo& rhs) noexcept
{
using std::swap;
std::lock_guard<std::mutex> lock_lhs {lhs.mutex_}, lock_rhs {rhs.mutex_};
swap(ls.str_, rhs.str_);
// swap everything else
}
I've seen that in C++17, std::lock_guard
will have a constructor taking multiple mutexes for avoiding deadlock, but I'm not sure if that's an issue here?