本文介绍了C ++不同的单例实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常以这种方式实现单例模式:

I usually implement the singleton pattern this way :

class Singleton
{
    public:
        virtual ~Singleton() {}

        static Singleton& GetInstance()
        {
            static Singleton instance;
            return instance;
        }

    private:
        Singleton();
        Singleton(const Singleton&);
        Singleton& operator=(const Singleton&);
}

最近我碰到了这个实现,这有点不同:

Recently, I ran into this implementation, which is slightly different :

class Singleton
{
    public:
        Singleton();
        virtual ~Singleton() {}

        static Singleton& GetInstance()
        {
            return instance;
        }

    private:
        Singleton(const Singleton&);
        Singleton& operator=(const Singleton&);

        static Singleton instance;
}

Singleton Singleton::instance;

哪个实现更好?

不要让构造函数私有(第二个实现)是危险的?

Isn't it dangerous not to make the constructor private (2nd implementation) ?

谢谢。

推荐答案

我不必重复关于在其他答案中进行的单身人士的懒惰建设的好处。

I need not repeat the good point about lazy construction of the singleton made in other answers.

让我补充一下:

public:
    Singleton();
    virtual ~Singleton() {}


设计师这个特殊的阶级感觉需要允许:

The designer of this particular class felt a need to allow:


  • 从这个 singleton 类派生说派生类叫做 DerSingleton

  • DerSingleton 可以有实例可以通过指向 Singleton (所以 DerSingleton 不是单例)的指针删除

  • derivation from this Singleton class, say the derived class is called DerSingleton
  • DerSingleton can have instances which can be deleted with a pointer to Singleton (so DerSingleton is not a singleton)

任何 DerSingleton 的实例也是一个 Singleton 实例根据定义,所以如果 DerSingleton 被实例化, Singleton 不是单例。

Any instance of DerSingleton is also a Singleton instance by definition, so it follows that if DerSingleton is instanciated, Singleton is not a singleton.

所以这个设计断言了两件事:

So this design asserts two things:


  • 这个类是单例

  • 这个课程是不是单身人士

  • this class is a singleton
  • this class is not a singleton

这篇关于C ++不同的单例实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:55