繁体   English   中英

禁止复制构造函数和赋值运算符singleton类

[英]prohibit copy constructor and assignment operator singleton class

我正在用C ++实现Singleton类,我想知道是否有必要将复制构造函数和赋值运算符声明为私有,以防万一我具有以下实现

class Singleton{

static Singleton* instance;

Singleton(){}

public:


static Singleton* getInstance();

};

Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance(){

    if(instance == 0){
        instance = new Singleton();
    }
    return instance;
} 

看来我只能有一个指向Singleton的指针,在这种情况下,复制构造函数是无用的,也是operator= 因此,我可以跳过将它们声明为私有的操作,我错了吗?

没有什么可以阻止某人写作

Singleton hahaNotReallyASingleton = *Singleton::getInstance();

您可以将这些功能专门标记为delete d

class Singleton {
    // ... other bits ...

    Singleton(Singleton const&) = delete; // copy ctor
    Singleton(Singleton &&)     = delete; // move ctor
    Singleton& operator=(Singleton const&) = delete; // copy assignment
    Singleton& operator=(Singleton &&)     = delete; // move assignment
};

请注意,以这种方式使用deleteC++11及更高版本-如果您使用的是较旧的代码库,则可以将函数设为 private (仅复制,当然不移动),或从boost:noncopyable继承(感谢badola ) 。

暂无
暂无

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

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