Poniżej znajduje się dobrze znana implementacja wzorca singleton w C++.
Jednak nie jestem do końca pewien, czy wątek bezpieczny.
Na podstawie odpowiedzi na podobne pytanie zadane poprzednio, wydaje się, że jest bezpieczny dla wątków.
Czy to prawda?Implementacja singleton safe thread w C++
//Curiously Recurring Template Pattern
//Separates a class from its Singleton-ness (almost).
#include <iostream>
using namespace std;
template<class T> class Singleton {
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
protected:
Singleton() {}
virtual ~Singleton() {}
public:
static T& instance() {
static T theInstance;
return theInstance;
}
};
// A sample class to be made into a Singleton
class MyClass : public Singleton<MyClass> {
int x;
protected:
friend class Singleton<MyClass>;
MyClass() { x = 0; }
public:
void setValue(int n) { x = n; }
int getValue() const { return x; }
};
Dlaczego zrobiłeś to WIKI? To całkowicie poprawne pytanie. – JaredPar
nie podałeś żadnych powodów, dla których * ty * uważasz, że implementacja wzorca nie jest bezpieczna dla wątków. Proszę zrób. – gogole
jaki jest cel klasy przyjaciół? czy ktoś może odpowiedzieć? –