I know that the singleton pattern is usually considered a bad design and hence discouraged, but this question concerns the implementation aspects, not the appropriateness of the singleton pattern.
Consider the following three implementations of a singleton in C++ using lazy initialization:
1: Using pointer, split between declaration and implementation
Singleton.hpp:
class Singleton {
public:
static Singleton* instance();
private:
Singleton() {}
static Singleton* singleton;
};
Singleton.cpp:
Singleton* Singleton::singleton = nullptr;
Singleton* Singleton::instance() {
if( nullptr == singleton ) {
singleton = new Singleton();
}
return singleton;
}
2: Using reference, split between declaration and implementation
Singleton.hpp:
class Singleton {
public:
static Singleton& instance();
private:
Singleton() {}
};
Singleton.cpp:
Singleton& Singleton::instance() {
static Singleton singleton;
return singleton;
}
3: Using reference, inline in declaration
Singleton.hpp:
class Singleton {
public:
static Singleton& instance() {
static Singleton singleton;
return singleton;
}
private:
Singleton() {}
}
I personally like and use the third version. But is there any good reason to prefer the first or the second version instead?
It is my understanding that in the third version there is an instance of the object for each translation unit that includes Singleton.hpp and then the linker picks a single one. Does this causes any side effect?
And are there any side effects using the third one in a shared library?
Bonus questions: which implementation is actually the "Meyer's singleton"?
Aucun commentaire:
Enregistrer un commentaire