美文网首页
实现 singleton 模式

实现 singleton 模式

作者: 朔方烟尘 | 来源:发表于2019-05-14 17:01 被阅读0次

https://stackoverflow.com/questions/1008019/c-singleton-design-pattern#

// C++ 03
class S03
{
public:
    static S03& getInstance()
    {
        static S03 instance; // Guaranteed to be destroyed.  Instantiated on first use.
        return instance;
    }

private:
    S03() {}                        // Constructor? (the {} brackets) are needed here.

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


// C++ 11
class S11
{
public:
    static S11& getInstance()
    {
        static S11 instance; // Guaranteed to be destroyed.  Instantiated on first use.
        return instance;
    }

private:
    S11() {}                        // Constructor? (the {} brackets) are needed here.

    // C++ 11
    // =======
    // We can use the better technique of deleting the methods we don't want.
public:
    S11(S11 const&) = delete;
    void operator=(S11 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
};

相关文章

  • 实现Singleton模式

    面试题 2实现Singleton模式

  • 实现 Singleton 模式

    题目:设计一个类,只能生成该类的一个实例 单例模式的组成: 使用一个私有构造函数、一个私有静态变量以及一个公有静态...

  • 实现Singleton模式

    题目:设计一个类,我们只能生成该类的一个实例题目其实说到底只是常见的单例模式,相信大家对这个最基础的设计模式早已有...

  • 实现Singleton模式

    什么是Singleton模式? 如何实现Singleton模式 解法一(只适用于单线程)由于只能生成一个实例,因此...

  • 实现 singleton 模式

    https://stackoverflow.com/questions/1008019/c-singleton-d...

  • 实现Singleton模式

    不好的解法-:只适用于单线程环境 设想如果两个线程同时运行到判断instance是否为null的if语句,并且in...

  • Python单例模式(Singleton)的N种实现

    Python单例模式(Singleton)的N种实现

  • go设计模式代码实现

    go 设计模式代码实现 单例模式 代码实现 type singleton struct{} var ins *si...

  • 单例模式

    Singleton模式 只有一个实例 1. Singleton模式 Singleton模式的目的: 想确保任何情况...

  • 单例模式

    单例模式及C++实现代码单例模式4种实现详解 c++11改进我们的模式之改进单例模式 单例模式(Singleton...

网友评论

      本文标题:实现 singleton 模式

      本文链接:https://www.haomeiwen.com/subject/kileaqtx.html