Home > Enterprise >  C : Can you have a static and a non-static instance of the same class when using the Singleton desi
C : Can you have a static and a non-static instance of the same class when using the Singleton desi

Time:12-10

I'm trying to understand what's happening under the hood with the following piece of code. The question that I'm having trouble with is: How are static instances of classes handled in c ?

#include <iostream>

using namespace std;

class Shape {
   public:

      static Shape& getInstance() {
         static Shape obj;
         static Shape& objRef = obj;
         return objRef;
      }

      void init() {
          Shape singleton = Shape::getInstance();
          srand((unsigned)time(0));
          singleton.width = rand()0;
          singleton.printWidth();
      }

      void printWidth(){
        cout<<width<<endl;
      }
      
   protected:
      int width = 0;
};

int main()
{
   Shape rectangle;
   rectangle.init();
   rectangle.printWidth();
   
   return 0;
}

The output of this code is:

37
0

But to me, this doesn't make sense. If a static instance of Shape is made anywhere within the program, shouldn't there only be one Shape in memory? If any shapes call printWidth after the singleton has set the width, shouldn't their width be equal to that width?

I would appreciate an explanation of where my thinking is going wrong.

CodePudding user response:

Singleton, by definition, means that you'll have only one instance.

However, static does not ensure it's singleton. Your code's getInstance() would like to be a common instance getter pattern: you have access to a common instance, but you can also create (arbitrary many) instances as required. So your local instance, rectangle, won't be the one that init() initializes. What's even worse, in your code, you returns a copy of the common instance, not a reference to it (e.g. static Shape& getInstance() would solve this), so you have 3 instances we're talking about: one in getInstance(), one in init() that's printed and then dropped; and one in main. If you fix it with reference return, you'll still need to use references (initialized by getInstance()) to make it work.

  • Related