简体   繁体   English

如何在类成员互斥上使用std :: lock_guard

[英]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. 在下面的代码中, bad方法无法编译,但good方法却没有。 Why is providing the explicit reference to this making a difference here? 为什么提供明确提到this使得这里的区别?

#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. 如果你愿意,你可以玩ideone

This is an instance of the most vexing parse. 这是最令人烦恼的解析的一个例子。 The parentheses here don't do what you think they do. 这里的括号不符合你的想法。 This: 这个:

std::lock_guard<std::mutex>(lock_);

is equivalent to: 相当于:

std::lock_guard<std::mutex> lock_;

which should make it clear why what you're trying to do won't compile, and why you're getting the compile error you're getting. 这应该清楚说明为什么你要做的事情不会编译,以及为什么你得到你得到的编译错误。 What you need to do is provide a name for the lock_guard : 您需要做的是为lock_guard提供一个名称:

std::lock_guard<std::mutex> _(lock_);

The good version works because the this-> qualification prevents the name from being able to be treated as an identifier. 好的版本有效,因为this->限定条件阻止名称被视为标识符。


Note: lock_ is a std::mutex and not any kind of lock, which makes it a very confusing name. 注意: lock_是一个std::mutex而不是任何类型的锁,这使得它成为一个非常混乱的名称。 You should name it something more reflective of what it is. 你应该把它命名为更能反映它是什么的东西。 Like mutex_ . mutex_

If you declare your lock_guard correctly, they both work: 如果您正确声明了lock_guard,它们都可以正常工作:

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

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

Using a temporary is almost useless, because the lock gets released immediately. 使用临时几乎是无用的,因为锁立即被释放。 Correct usage is to declare a local variable with automatic lifetime. 正确的用法是声明具有自动生命周期的局部变量。

例如,您需要实际创建变量

std::lock_guard<std::mutex> lg(lock_);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM