C++中的单例模式

2018-02-07  本文已影响4人  ME_HK
#include <iostream>
#include <memory>

class singleton {
public:
    singleton() = default;

    // 禁止拷贝构造
    singleton(singleton const &) = delete;

    // 禁止赋值
    singleton &operator=(singleton const &) = delete;

    virtual ~singleton() = default;
public:
    // 返回智能指针,保证创建的对象可以被销毁
    static std::shared_ptr<singleton> get_instance() {
        static std::shared_ptr<singleton> ins(new singleton());
        return ins;
    };

// for test
public:
    void hello() {std::cout << "hello, world!" << std::endl;}
};

int main() {
    auto s = singleton::get_instance();
    s->hello();

    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读