关于单例模式:C单例模式实现

最不便罕用的是Meyers’ Singleton,多线程平安。gcc 4.0之后的编译器反对这种写法,要求C++11及其当前的版本。

class Singleton
{
public:
    // 留神返回的是援用
    static Singleton &getInstance()
    {
        static Singleton instance;  // 动态局部变量
        return instance;
    }

private:
    Singleton() = default;
    Singleton(const Singleton &) = delete; // 禁用拷贝构造函数
    Singleton &operator=(const Singleton &) = delete; // 禁用拷贝赋值运算符
};

残缺的验证程序:

#include <iostream>
using namespace std;

class Singleton
{
public:
    // 留神返回的是援用
    static Singleton &getInstance()
    {
        static Singleton instance;  // 动态局部变量
        return instance;
    }

private:
    Singleton() = default;
    Singleton(const Singleton &) = delete; // 禁用拷贝构造函数
    Singleton &operator=(const Singleton &) = delete; // 禁用拷贝赋值运算符
};

int main()
{
    Singleton& s1 = Singleton::getInstance(); // &是援用
    cout << &s1 << endl; // &是取地址

    Singleton& s2 = Singleton::getInstance();
    cout << &s2 << endl;

    // Singleton s3(s1);

    // s2 = s1;

    system("pause");

    return 0;
}

打印出s1和s2的地址是同一个,因为是同一个动态局部变量

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理