K
K
Konstantin Knatarev2019-08-06 21:48:01
C++ / C#
Konstantin Knatarev, 2019-08-06 21:48:01

I'm studying patterns, I have a question about the Singleton pattern, should it look something like this?

Now I’m busy with patterns, the next step is Singleton, I correctly understood that it should look something like this (in all sources they are written differently), tell me the most clear and accurate implementation.
Looks like this for me:

#include <iostream>

class Singleton {
public:
    static Singleton* Instance() {
        if (instance == 0) {
            instance = new Singleton;
        }
        return instance;
    }
protected:
    Singleton();
private:
    static Singleton* instance;
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
krs, 2019-08-06
@tujhan

Something like this, but it's better to forbid copying

Singleton(Singleton const&) = delete;
Singleton& operator= (Singleton const&) = delete;

M
menkar3, 2019-08-21
@menkar3

I would recommend the Myers version . At least because of the thread-safe initialization.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question