Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize class members in singleton pattern?

Tags:

c++

singleton

I've a class following singleton approach, but where do i initialize class members 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;
    }
};
like image 667
user963241 Avatar asked Mar 04 '11 18:03

user963241


2 Answers

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

The constructor is private to the outside world, not to the static member function Instance(). That means, the line static MyClass singleton in Instance() actually invokes default constructor, and that is valid, as Instance() has access to private members of the class!

like image 72
Nawaz Avatar answered Sep 21 '22 22:09

Nawaz


In the constructor, that's what it's there for. It has full access to members.

Also, be aware that this is unsafe in a multi-threaded application.

like image 44
Erik Avatar answered Sep 21 '22 22:09

Erik