In my program I'm using one of the most common Singleton pattern used in C++ that I enhanced logically with the arrival of C++11, here is my final code :
template <class T>
class Singleton {
public:
~Singleton() = default;
static T& getInstance() {
if (instance.get() == nullptr)
instance = std::shared_ptr<T>(new T());
return *instance;
}
static void killInstance() {
instance = std::shared_ptr<T>(nullptr);
}
protected:
Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
static std::shared_ptr<T> instance;
};
template <typename T>
std::shared_ptr<T> Singleton<T>::instance(nullptr);
So all over the internet we can see this pattern taught on many sites, but I have one issue with it, in every single sites I found, it is said that every singleton must be declared this way :
class MySingleton : public Singleton<MySingleton> {
friend classSingleton<MySingleton>
};
But as far as I remember, the standard (and not only since C++11) clearly states that a class is automatically the friend of all of its children (on the contrary children are not since they it's based on parent's accessibility and inheritance's accessibility), which quite honestly makes sense. So this friend statement I see everywhere really look quite useless AND senseless isn't it? Anyone can confirm I can get rid of it without any issue?
Thanks in advance everyone ;)