Skip to content

C++11 单例模式

注意:单例模式会让程序变得难以测试,所以尽可能不要使用单实例模式。

保证一个类只有一个实例,并且提供了访问该实例的全局访问点。

线程安全的单例模式-C++11

Singleton.h

cpp
#pragma once

template<typename T>
class Singleton
{
public:
    static T& instance() {
        static T instance{ token{} };
        return instance;
    }

    Singleton(const Singleton&) = delete;
    Singleton& operator= (const Singleton) = delete;

protected:
    struct token {};
    Singleton() {}
};

Example

cpp
#include <Singleton.h>
#include <iostream>
class Test final : public Singleton<Test>
{
public:
    Test(token) { std::cout << "constructed" << std::endl; }
    ~Test() {  std::cout << "destructed" << std::endl; }

    void use() const { std::cout << "in use" << std::endl; };
};

int main()
{
    // Test cannot_create; /* ERROR */

    std::cout << "Entering main()" << std::endl;
    {
        auto const& t = Test::instance();
        t.use();
    }
    {
        auto const& t = Test::instance();
        t.use();
    }
    std::cout << "Leaving main()" << std::endl;
}

隐患

如果单例类位于 dll 库中,是否还能保证唯一?

参考文献

1.https://codereview.stackexchange.com/questions/173929/modern-c-singleton-template

2.https://stackoverflow.com/questions/8102125/is-local-static-variable-initialization-thread-safe-in-c11

3.https://gameprogrammingpatterns.com/singleton.html

4.https://gpp.tkchu.me/singleton.html