实现 singleton 模式

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 模式)