【发布时间】:2014-07-09 09:18:17
【问题描述】:
我有以下单例策略类实现:
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;
}
};
然后我通过奇怪的重复模板模式 (CRTP) 使用它
class Foo: public Singleton<Foo> // now Foo is a Singleton
{
friend class Singleton<Foo>;
~Foo(){}
Foo(){};
public:
// rest of the code
};
我不明白为什么要删除移动构造函数和赋值运算符。你能给我一个例子,如果我不删除(根本不定义)移动 ctor 和赋值运算符,我最终会破坏单例吗?
【问题讨论】:
-
你应该在哪里读到的?
-
没有理由,你不必那样做。
-
@LightnessRacesinOrbit 在这里例如:stackoverflow.com/a/15187331/3093378 我记得在其他一些代码示例中看到过它,尽管我不记得了。我想知道为什么,因为我认为如果我删除复制 ctor,则不会隐式定义移动 ctor
-
您实际分配/移动的用例是什么,否则要求为这种情况提供语言定义?
-
@πάνταῥεῖ 我试图看看我是否真的需要将其声明为已删除(即,如果没有,是否有可能通过以某种方式在向量中移动 @ 返回的对象来打破单例模式987654324@,即使实例失效。)
标签: c++ c++11 singleton move-semantics