Suppose I have the following singleton base class:
template <class Derived>
class Singleton
{
public:
inline static Derived* get();
protected:
Singleton();
~Singleton();
static std::unique_ptr<Derived> _uptr;
private:
Singleton(const Singleton&);
Singleton & operator = (const Singleton&);
};
// Initialize the singleton object.
template <class Derived>
std::unique_ptr<Derived> Singleton<Derived>::_uptr = nullptr;
// Constructor
template <class Derived>
Singleton<Derived>::Singleton() {
}
// Constructor
template <class Derived>
Singleton<Derived>::~Singleton() {
}
// Function: get
template <class Derived>
inline Derived* Singleton<Derived>::get() {
if(_uptr != nullptr) return _uptr.get();
std::unique_ptr<Derived> tmp(new Derived());
_uptr = std::move(tmp);
return _uptr.get();
}
And I have the following derived classes:
class Foo : public Singleton <Foo> {
public:
int value;
}
int main() {
Foo A;
Foo B;
A.value = 1;
B.value = 2;
A.get()->value = 3;
cout << A.value << endl; // we get 1
cout << B.value << endl; // we get 2
cout << A.get()->value() << " " << B.get()->value() << endl; // we get 3
}
I am wondering why the three methods give completely different outputs on value. Shouldn't A and B return the same value as they inherit the same singleton base? To be more specific, I wanna implement a class that has global scope and will be initiated only once.
Foo A; Foo B;A Singleton where you have 2 instances actually, isn't that contradictory? I think you have some serious misconceptions here. You should actually prevent, that more than a single instance of that class can be created.