0

I've found this singleton example in C++ language:

#include <iostream>

class singleton {
private:
    // ecco il costruttore privato in modo che l'utente non possa istanziare direttamante
    singleton() { };
public:
    static singleton& get_instance() 
    {
            // l'unica istanza della classe viene creata alla prima chiamata di get_instance()
            // e verrà distrutta solo all'uscita dal programma
        static singleton instance;
        return instance;
    }
    bool method() { return true; };
};

int main() {
    std::cout << singleton::get_instance().method() << std::endl;

    return 0;
}

But, how can this be a singleton class?

Where is the control of only one istance is created?

Do not miss a static attribute?

What happens if in main function I write another get_instance() call?

sergej
  • 17,147
  • 6
  • 52
  • 89
hteo
  • 315
  • 1
  • 4
  • 11

2 Answers2

3

The one-instance control is done using the function-scope static inside get_instance. Such objects are constructed once upon program flow first passing through them and destructed at program exit. As such, the first time you call get_instance, the singleton will be constructed and returned. Every other time the same object will be returned.

This is often known as the Meyers singleton.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
1

I'd like to point you to a rather general description of the pattern and then to a deeper dissertation with a C++ example. It seems to me more effective than trying to explain (once more again).

P.S. And yes, you need some static definition too.

EnzoR
  • 3,107
  • 2
  • 22
  • 25