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?

5
  • Have you searched the web for "c++ singleton"? There are many examples to compare to. Commented May 6, 2014 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 about whether the anti-pattern makes sense in your program. Commented May 6, 2014 at 14:00
  • 1
    Personally, I think singleton is a really bad idea. Commented May 6, 2014 at 14:00
  • Singletons are just a fancy way of dressing up a global variable. Commented May 6, 2014 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. Commented May 7, 2014 at 7:31

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.