mercredi 25 mai 2016

When C++ const methods synchronize mutable state, do non-const methods have to do so too?

According to Herb Sutter (http://ift.tt/131MKLT), in C++11 const methods must not alter the object bit-wise, or must perform internal synchronization (e.g. using a mutex) if they have mutable data members.

My question is, do non-const methods have to acquire the mutex too? Or can they rely on the external synchronization their user will have to perform if the user wants to mix const and non-const methods on the same object concurrently?

Put another way, is the following class thread-safe?

#include <thread>

class C {
  public:
  void const_method() const
  {
    std::lock_guard<std::mutex> g(m);
    i = 2;
  }

  void non_const_method()
  {
    // std::lock_guard<std::mutex> g(m); // <-- is this needed?
    i = 1;
  }

  private:
  mutable int i;
  mutable std::mutex m;
};

Aucun commentaire:

Enregistrer un commentaire