How to initialize class members in a singleton template?

I have a class following the singleton approach, but where do I initialize the members of the class if its constructor is private?

class MyClass
{
    MyClass() {};                //constructor is private         
    MyClass(const MyClass&);            
    MyClass& operator=(const MyClass&);
public:
    static MyClass& Instance()
    {
        static MyClass singleton;
        return singleton;
    }
};
+5
source share
3 answers

You can initialize class members in the constructor itself, as usual, even be private.

The constructor is closed to the outside world, not to a static member function Instance(). This means that the string static MyClass singletonin Instance()actually calls the default constructor, and this is true because it Instance()has access to privateclass members!

+12
source

, . .

, , .

+3

The Instance method calls the constructor. The Instance method is static, so you can access it without creating it, and since it is a member, it can call a private constructor.

Then your constructor can do any necessary initialization.

Aside, your singleton member should be a pointer.

0
source

All Articles