There are two classes: A and B. A is Sigleton, B is a simple class (for example). So, different objects of class A are in no way connected with each other.

#include <iostream> using namespace std; class B { public: B(int a, int b) { this->a = a; this->b = b; } int a, b; }; class A {//singleton private: A(){} public: int x, y; B* b; static A getInstance() { static A instance; return instance; } bool operator==(const A& a) { return ax == this->x && ay == this->y; } }; void main() { A* a1 = &A::getInstance(); A* a2 = &A::getInstance(); a1->x = 121; a1->b = new B(65, 12); cout << a2->b->a << endl; system("pause"); } 

In this case, a1.x=121 , a1.y=0 , a1.ba=65 , a1.bb=12 , and for an object a2 - default values ​​( a2.x=0 , a2.y=0 , a2.b=NULL ). What's happening?!

  • A is Sigleton and various objects of class A - this is nonsense! There can not be several singleton objects in one program! - Harry

1 answer 1

You return copies of the object (by the way, by closing the default constructor, you did not close the copy constructor!):

 static A getInstance() { static A instance; return instance; } 

Need to return the link -

 static A& getInstance() { static A instance; return instance; } 

In general, it is not clear what is happening and how it is compiled:

 A* a1 = &A::getInstance(); 

You get a pointer to a temporary object ...

  • Thank you for the edits and answer! - Romeon0
  • Well, if the answer suits you - mark as accepted. - Harry