开发者

How to initialize class members in singleton pattern?

开发者 https://www.devze.com 2023-02-15 08:36 出处:网络
I\'ve a class following singleton approach, but where do i initialize class members if its constructor is private?

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;
    }
};


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!


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.


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

Your constructor can then do any necessary initialization.

As an aside, your singleton member should be a pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号