Home c++ Singleton and implementation

Singleton and implementation




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
  static Singleton & amp; Instance ()
    // according to the standard, this code is lazy and thread safe
    static Singleton s;
    return s;
  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:

  1. 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.
  2. Ditto for the copy constructor.
  3. 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.
  4. 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 ();

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions