最近,我遇到了C++的Singleton设计模式的实现/实现。它看起来是这样的(我采用了现实生活中的例子):

// a lot of methods are omitted here
class Singleton
{
   public:
       static Singleton* getInstance( );
       ~Singleton( );
   private:
       Singleton( );
       static Singleton* instance;
};

从这个声明中,我可以推断实例字段是在堆上启动的。这意味着存在内存分配。对我来说完全不清楚的是,内存将在何时被释放?或者是否存在错误和内存泄漏?似乎在实现方面存在问题。

我的主要问题是,如何以正确的方式实现它?


当前回答

@洛基·阿斯塔里的回答很好。

然而,有时使用多个静态对象时,您需要能够保证在所有使用单例的静态对象不再需要它之前,单例不会被破坏。

在这种情况下,std::shared_ptr可用于保持所有用户的单例有效,即使在程序结束时调用静态析构函数:

class Singleton
{
public:
    Singleton(Singleton const&) = delete;
    Singleton& operator=(Singleton const&) = delete;

    static std::shared_ptr<Singleton> instance()
    {
        static std::shared_ptr<Singleton> s{new Singleton};
        return s;
    }

private:
    Singleton() {}
};

其他回答

@洛基·阿斯塔里的回答很好。

然而,有时使用多个静态对象时,您需要能够保证在所有使用单例的静态对象不再需要它之前,单例不会被破坏。

在这种情况下,std::shared_ptr可用于保持所有用户的单例有效,即使在程序结束时调用静态析构函数:

class Singleton
{
public:
    Singleton(Singleton const&) = delete;
    Singleton& operator=(Singleton const&) = delete;

    static std::shared_ptr<Singleton> instance()
    {
        static std::shared_ptr<Singleton> s{new Singleton};
        return s;
    }

private:
    Singleton() {}
};

另一个非分配的选择:根据需要创建一个单例,比如C类:

singleton<C>()

使用

template <class X>
X& singleton()
{
    static X x;
    return x;
}

在当前C++中,这一点和Cætælin的答案都不是自动线程安全的,而是在C++0x中。

这里是一个使用CRTP的可模拟单例。它依赖于一个小助手在任何时候(最多)强制执行一个对象。要在程序执行过程中强制执行单个对象,请删除重置(我们发现这对测试很有用)。

ConcreteSinleton可以这样实现:

class ConcreteSingleton : public Singleton<ConcreteSingleton>
{
public:
  ConcreteSingleton(const Singleton<ConcreteSingleton>::PrivatePass&)
      : Singleton<StandardPaths>::Singleton{pass}
  {}
  
  // ... concrete interface
  int f() const {return 42;}

};

然后与一起使用

ConcreteSingleton::instance().f();

2008年,我提供了一个Singleton设计模式的C++98实现,该模式是惰性评估的、保证破坏的,在技术上不是线程安全的:有人能给我提供一个c++中的Singleton示例吗?

这里是Singleton设计模式的一个更新的C++11实现,它是延迟评估的、正确销毁的和线程安全的。

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        S() {}                    // Constructor? (the {} brackets) are needed here.

        // C++ 03
        // ========
        // Don't forget to declare these two. You want to make sure they
        // are inaccessible(especially from outside), otherwise, you may accidentally get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement

        // C++ 11
        // =======
        // We can use the better technique of deleting the methods
        // we don't want.
    public:
        S(S const&)               = delete;
        void operator=(S const&)  = delete;

        // Note: Scott Meyers mentions in his Effective Modern
        //       C++ book, that deleted functions should generally
        //       be public as it results in better error messages
        //       due to the compilers behavior to check accessibility
        //       before deleted status
};

请参阅本文,了解何时使用单例:(不经常)辛格尔顿:应该如何使用

请参阅这两篇关于初始化顺序和如何处理的文章:静态变量初始化顺序查找C++静态初始化顺序问题

请参阅这篇描述寿命的文章:C++函数中静态变量的生存期是多少?

请参阅本文,其中讨论了单线程的一些线程含义:Singleton实例声明为GetInstance方法的静态变量,它是线程安全的吗?

请参阅这篇文章,解释为什么双重检查锁定在C++上不起作用:C++程序员应该知道哪些常见的未定义行为?Dobbs博士:C++和双重检查锁定的危险:第一部分

以下是我对如何实现正确的单线图(以及其他非平凡静态对象)的看法:https://github.com/alex4747-pub/proper_singleton

摘要:

使用静态初始化列表在正确的时间实例化单线程:在进入main之后和启用多线程之前添加一些小的改进,使其对单元测试友好。