mardi 29 septembre 2015

How to use std::lock_guard on a class member mutex

In the following code the bad method fails to compile, but the good method does not. Why is providing the explicit reference to this making a difference here?

#include <mutex>

class Foo
{
 private:
  std::mutex lock_;

 public:
  Foo() = default;
  ~Foo() = default;

  void bad();
  void good();
};

void Foo::bad()
{
  std::lock_guard<std::mutex>(lock_);
}

void Foo::good()
{
  std::lock_guard<std::mutex>(this->lock_);
}

int main()
{
  return 0;
}

compile error:

test.cpp: In member function ‘void Foo::bad()’:
test.cpp:18:36: error: no matching function for call to ‘std::lock_guard<std::mutex>::lock_guard()’
   std::lock_guard<std::mutex>(lock_);

You can play with the ideone if you want.

Aucun commentaire:

Enregistrer un commentaire