Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: Can you have a static and a non-static instance of the same class when using the Singleton design pattern?

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()%100;
          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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading