1

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 ?

loannnlo
  • 111
  • 1
  • 6
  • 1
    Possible duplicate of [why explicitly delete the constructor?](https://stackoverflow.com/questions/13654927/why-explicitly-delete-the-constructor) – mch Jul 17 '18 at 07:12
  • 1
    If you don't want those operations or they are not valid/sane for the class, then you *should* `=delete;` the functions. – Jesper Juhl Jul 17 '18 at 07:12

1 Answers1

3

There's nothing to stop someone writing

Singleton hahaNotReallyASingleton = *Singleton::getInstance();

You can specifically mark these functions as deleted:

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).

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • thank you, I haven't considered that case, I thought I cannot have object of that class – loannnlo Jul 17 '18 at 07:19
  • 1
    Kindly note that deleted functions are only allowed C++11 and above. For pre-C++11, a construct similar to `boost::noncopyable` would be required. – badola Jul 17 '18 at 08:21