1

I am trying to implement the singleton pattern in c++.

static class_test* getinstance()
{
   static class_test single_obj;
   return &single_obj;
}

If i want to create singleton object i will go with this method.

class_test *c = class_test :: getinstance();

So it is ensured that single object is maintained everytime.

But in the same program i have used the following statement

class_test test;

This also seems to be works. I think it is a violation of singleton pattern.

Is my understanding is correct?

Or the implementation of the singleton pattern is left with hands of programmer?

VINOTH ENERGETIC
  • 1,775
  • 4
  • 23
  • 38
  • Have you searched the web for "c++ singleton"? There are many examples to compare to. – Thomas Matthews May 06 '14 at 13:59
  • 4
    You can prevent multiple instances by making the constructor private, so only the accessor function (a static member) can create it. But [think twice](http://stackoverflow.com/questions/137975) about whether the anti-pattern makes sense in your program. – Mike Seymour May 06 '14 at 14:00
  • 1
    Personally, I think [singleton is a really bad idea](http://stackoverflow.com/q/137975/10077). – Fred Larson May 06 '14 at 14:00
  • Singletons are just a fancy way of dressing up a global variable. – tacaswell May 06 '14 at 14:10
  • Only if it's globally accessible. A singleton means there should only be one instance of it. It could still be dependency injected. – Jonatan Hedborg May 07 '14 at 07:31

2 Answers2

4

You should declare class_test::class_test() as private to prevent user from instantiating new objects.

timrau
  • 22,578
  • 4
  • 51
  • 64
2

Here's what you should do:

  1. make all constructors of class_test private. This way, only class_test::getinstance (see the next point) will have access to the constructor.

  2. make getinstance, a static function of class_test (so it will have access to the constructors)

  3. make the destructor public (this is the default so you shouldn't have to do anything really)

That said, you should probably not use singletons in production code, as they introduce places in code that make refactoring and loose coupling difficult.

Consider using dependency injection instead.

utnapistim
  • 26,809
  • 3
  • 46
  • 82