简体   繁体   English

C++ 如何初始化包含互斥锁的 class 的 static 变量

[英]C++ How to initialize static variable of an class which contains a mutex

I have a templated class with a mutex:我有一个带有互斥锁的模板 class:

template <typename T> class A {
 public:
  std::mutex classMutex;
  T value;
  A(T initValue) : value(initValue){}
};   

and a second class with a static member of the first class:和第二个 class 和第一个 class 的 static 成员:

class B{
  static A<double> test;
}; 
A<double> B::test = 0.0;

I keep getting an error: "copying variable of type 'A' invokes deleted constructor"我不断收到错误消息:“复制 'A' 类型的变量调用已删除的构造函数”

Thanks to @rafix07:感谢@rafix07:

The solution is:解决方案是:

A<double> B::test{0.0};

"mutex is neither copyable nor movable, it means all copy and move operations are deleted by default (for class which contains mutex as data variable) “互斥量既不可复制也不可移动,这意味着默认情况下会删除所有复制和移动操作(对于包含互斥量作为数据变量的 class)

 A(const A&) = delete,
 A(A&&) = delete 

etc. When you call等当你打电话时

A<double> B::test = 0.0 

double value 0.0 is converted to双精度值 0.0 转换为

A<double>(0.0) 

so you have所以你有了

A<double> B::test = A<double>(0.0) 

because copy construction is deleted compiler refuse this line.因为复制构造被删除编译器拒绝这一行。 With {} you are just calling A(0.0) constructor without any copy syntax." by @rafix07使用 {},您只需调用 A(0.0) 构造函数,而无需任何复制语法。” by @rafix07

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

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