I am trying to implement a simple singleton pattern in 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;
}
My question is about the multiple constructors available for simpleSingleton
class
simpleSingleton(){}' 'simpleSingleton(const simpleSingleton& rs)
A constructor is expected to return an object of the class. In the above example neither of the constructors have a return statement. Yet this seems to be standard simpleton implementation. why is that?
Aucun commentaire:
Enregistrer un commentaire