在我的程序中,我正在使用C ++中使用的最常见的Singleton模式之一,随着C ++ 11的到来,我在逻辑上进行了增强,这是我的最终代码:
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);
所以在整个互联网上我们可以看到这个模式在许多网站上讲授,但我有一个问题,在我发现的每个网站中,据说必须以这种方式声明每个单身:
class MySingleton : public Singleton<MySingleton> {
friend classSingleton<MySingleton>
};
但据我记忆,标准(不仅仅是自C ++ 11以来)明确指出一个类自动成为所有孩子的朋友(相反,孩子不是因为他们是基于父母的可访问性和继承的可访问性),老实说是有道理的。所以这个朋友的声明,我到处看到真的看起来很无用而且毫无意义不是吗?任何人都可以确认我可以毫无问题地摆脱它吗?
先谢谢大家;)
答案 0 :(得分:2)
但据我记忆,标准(不仅仅是自C ++ 11以来) 明确指出一个班级自动成为所有班级的朋友 儿童
这是一种误解。这些概念是正交的:一个类不是其子女的朋友。