简体   繁体   中英

prohibit copy constructor and assignment operator singleton class

I am implementing Singleton class in c++ and I am wondering if it is necessary to declare copy constructor and assignment operator as private, in case I have the following implementation

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

It seems that I can have only pointer to Singleton and in that case copy constructor is useless, also operator= . So, I can skip declaring these as private, am I wrong ?

There's nothing to stop someone writing

Singleton hahaNotReallyASingleton = *Singleton::getInstance();

You can specifically mark these functions as 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
};

Note that using delete in this way is C++11 and onwards - if you are stuck with an older codebase, you could make the functions private (copy only, not move of course), or inherit from boost:noncopyable (thanks badola ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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