hteo
hteo

Reputation: 335

singleton example how works

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?

Upvotes: 0

Views: 465

Answers (2)

EnzoR
EnzoR

Reputation: 3346

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.

Upvotes: 1

TartanLlama
TartanLlama

Reputation: 65580

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.

Upvotes: 3

Related Questions