Singleton pattern confusion in C++
-
Hi,
I have been trying to implement a singleton pattern example but it’s causing a lot of difficulties, below is my example:
// Singleton.h class Singleton { private: Singleton() {} int a, b; static Singleton *obj; public: Singleton(const Singleton &); static Singleton &getObject(); } // Singleton.cpp Singleton *Singleton::instance = 0; // Need to keep copy constructor as it is. Singleton::Singleton(const Singleton &other) { // to copy the a and b values } Singleton &Singleton::getObject() { return obj; } int main() { Singleton obj = Singleton::getObject(); court << &obj << endl; court << &Singleton::getObject(); << endl; return 0; }
In the above example, the address of both objects is different in the output, why? How can I solve this?
Thanks in advance and looking forward.
Merry Christmas everyone.
10
-
@2k10cs86 sagte in Singleton pattern confusion in C++:
Singleton obj = Singleton::getObject();
This line creates a copy!
Disable the copy constructor when using a singleton. Why the hell are you implementing a copy constructor in a singleton? That's contradictory.
Here:
Singleton::Singleton(const Singleton &other) { // to copy the a and b values }
Why copy a singleton? The point of a singleton is that you cannot copy it.
You might want to look up "Meyer's Singleton" for an alternative implementation (if you really really really need a singleton).