If I create a class as a loner, do I need to implement the assignment operator, copy constructor, class comparison operators, etc.? How do you write them down at all? Simple without declaring but not writing an implementation?
And at the same time I will ask how to implement Singleton, if the class object will be created as
Class * c = new Class ();
not like this
Class c;
Answer 1, authority 100%
The classic (and most elegant) method for declaring a singleton in C++ is Myers’ singleton. Example:
class Singleton
{
public:
static Singleton & amp; Instance ()
{
// according to the standard, this code is lazy and thread safe
static Singleton s;
return s;
}
private:
Singleton () {...} // no constructor available
~ Singleton () {...} // and destructor
// you must also disable copying
Singleton (Singleton const & amp;); // no implementation needed
Singleton & amp; operator = (Singleton const & amp;); // and here
};
Starting with C++ 11, it is more correct to write like this:
Singleton (Singleton const & amp;) = delete;
Singleton & amp; operator = (Singleton const & amp;) = delete;
Now point by point:
- No assignment operator needed. Since in many cases it is created by the compiler behind your back, you need to declare it private so that no one can use it. In C++ 11, you can remove it directly with the “
= delete
” construct. - Ditto for the copy constructor.
- There is no need for comparison operators, since there is still only one instance. Since comparison operators are not automatically generated, you don’t need to worry about anything.
-
You cannot use a singleton by creating it explicitly: after all, if you could declare one instance, you can declare as many as you like! Therefore, we excluded the options for “manual” creation by making the constructor private. The only way to get a link to a singleton to work with it is:
Singleton & amp; instance = Singleton :: Instance ();