c++ - 为什么要在单例中删除 move 构造函数和 move 赋值运算符?

标签 c++ c++11 singleton move-semantics

我有以下单例策略类实现:

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
};

我不明白为什么要删除 move 构造函数和赋值运算符。你能给我一个例子,如果我不删除(根本不定义) move ctor 和赋值运算符,我最终会破坏单例吗?

最佳答案

如果你声明了一个复制构造函数(即使你在声明中将它定义为deleted),也不会隐式声明任何 move 构造函数。参照。 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 does not have a user-declared copy constructor,

— ...

由于您确实有一个用户声明的复制构造函数,因此如果您不声明一个 move 构造函数,则根本就不会有 move 构造函数。所以你可以完全摆脱 move 构造函数声明定义。 move 赋值运算符也是如此。

关于c++ - 为什么要在单例中删除 move 构造函数和 move 赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23771194/

相关文章:

c++ - 返回类型名称与 C++ 中的方法名称冲突

c++ - 比较将整数值转换为字符串的 3 种现代 C++ 方法

C++ 单例用法 : compiler complains about private constructor

java - 为什么 Spring 单例范围的 bean 比经典的单例模式更好?

c# - 连接到 Exchange - 入门教程?

c++ - 输出变量到文本文件

c++ - 非常基本的正则表达式场景与我对 libstdc++-v3 的预期不同

c++ - Boost元函数类高阶函数

qt - Qt 的 GUI 编程中的单例是邪恶的吗?

C++ 库 "internal use only"编码风格