template <typename T>
class Singleton
{
public:
static T& GetInstance()
{
static T instance;
return instance;
}
private:
//Cant do this
//Singleton(){};
};
class Foo : public Singleton<Foo>
{
};
I would like to make any class that inherits from Singleton non constructable as well (So that the only way to interact with it is by using the GetInstance() function), but the problem is that if i declare Singletons constructor as private then i get an error on line 7 where the static instance is being constructed :\
So i was just wondering if there is a way around this?
My terminology has always been a little casual, but wouldn't inherit of a singleton into more than one object be creation of multiples of the singleton, invalidating its contract? Granted the syntax lets you do whatever, but conceptually speaking, here...? Unless the singleton is static and shared across all the classes?
I apologize for adding a post in a thread that has already been marked as solved, but I think the problem on line 7 is related to what the method GetInstance() is required to return.
In the most common implementation of the (today often disapproved) singleton pattern, the so called 'Mayers singleton', GetInstance() returns an instance of the singleton class itself:
1 2 3 4 5 6 7 8 9 10 11 12 13
// I think it is known as 'Mayer singleton':
class MySingleton{
public:
static MySingleton& getInstance() {
static MySingleton instance;
return instance;
}
private:
MySingleton() = default;
~MySingleton() = default;
MySingleton(const MySingleton&) = delete;
MySingleton& operator=(const MySingleton&)= delete;
};
Anyway, as far as I know, the monostate pattern is often considered a good ‘replacement’ for the singleton one also because it’s easier to inherit.
And it is less criticized.