[英]Why should I delete move constructor and move assignment operator in a singleton?
I have the following Singleton policy-class implementation: 我有以下Singleton策略类实现:
template <typename T>
class Singleton
{
Singleton(){}; // so we cannot accidentally delete it via pointers
Singleton(const Singleton&) = delete; // no copies
Singleton& operator=(const Singleton&) = delete; // no self-assignments
Singleton(Singleton&&) = delete; // WHY?
Singleton& operator=(Singleton&&) = delete; // WHY?
public:
static T& getInstance() // singleton
{
static T instance; // Guaranteed to be destroyed.
// Instantiated on first use.
// Thread safe in C++11
return instance;
}
};
which I then use via the curiously recurring template pattern (CRTP) 然后我通过奇怪的重复模板模式(CRTP)使用
class Foo: public Singleton<Foo> // now Foo is a Singleton
{
friend class Singleton<Foo>;
~Foo(){}
Foo(){};
public:
// rest of the code
};
I cannot figure out why I should delete the move constructor and assignment operator. 我无法弄清楚为什么我应该删除移动构造函数和赋值运算符。 Can you give me a single example where I end up breaking the singleton if I don't delete (don't define at all) the move ctor and assignment operator?
你能给我一个例子,如果我不删除(根本没有定义)移动ctor和赋值运算符,我最终会破坏单例吗?
If you declare a copy constructor (even if you define it as delete
d in the declaration), no move constructor will be declared implicitly. 如果声明了一个复制构造函数(即使在声明中将其定义为
delete
d),也不会隐式声明移动构造函数。 Cf. 参看 C++11 12.8/9:
C ++ 11 12.8 / 9:
If the definition of a class
X
does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if如果类
X
的定义没有显式地声明一个移动构造函数,那么当且仅当一个移动构造函数被隐式声明为默认值时— X does not have a user-declared copy constructor,
- X没有用户声明的复制构造函数,
— ...
- ......
Since you do have a user-declared copy constructor, there won't be a move constructor at all if you don't declare one. 由于您确实拥有用户声明的复制构造函数,因此如果您没有声明复制构造函数,则根本不会有移动构造函数。 So you can just get rid of the move constructor declaration-definition entirely.
所以你可以完全摆脱移动构造函数声明定义。 Same for the move-assignment operator.
移动赋值运算符也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.