我正在尝试用C ++实现一个简单的单例模式。
#include <iostream>
class simpleSingleton
{
private:
static simpleSingleton * pInstance;
simpleSingleton(){}
simpleSingleton(const simpleSingleton& rs) {
pInstance = rs.pInstance;
}
simpleSingleton& operator = (const simpleSingleton& rs)
{
if (this != &rs)
{
pInstance = rs.pInstance;
}
return *this;
}
~simpleSingleton(){};
public:
static simpleSingleton& getInstance()
{
static simpleSingleton theInstance;
pInstance = &theInstance;
return *pInstance;
}
void demo()
{
std::cout << "simple singleton."
<< std::endl;
}
};
simpleSingleton *simpleSingleton::pInstance = nullptr;
int main()
{
/*Version 1 */
simpleSingleton * p = &simpleSingleton::getInstance(); // cache instance pointer p->demo();
p->demo();
/*Version 2 */
simpleSingleton::getInstance().demo();
return 0;
}
我的问题是关于simpleSingleton
类
simpleSingleton(){}'
'simpleSingleton(const simpleSingleton& rs)
构造函数应该返回该类的对象。在上面的示例中,两个构造函数都没有return语句。然而,这似乎是标准的简单实现。那是为什么?
答案 0 :(得分:2)
如果你使用单身人士,请使用迈耶斯的单身人士:
class Singleton
{
private:
Singleton() = default; // Adapt here
~Singleton() = default; // Adapt here
Singleton(const simpleSingleton& rs) = delete;
Singleton& operator = (const simpleSingleton&) = delete;
public:
Singleton& GetInstance()
{
static Singleton instance;
return instance;
}
};