前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++ 11 - singleton

C++ 11 - singleton

作者头像
Reck Zhang
发布2021-08-11 11:03:23
4130
发布2021-08-11 11:03:23
举报
文章被收录于专栏:Reck Zhang

singleton

代码语言:javascript
复制
// T must be: no-throw default constructible and no-throw destructible
template <typename T>
struct Singleton
{
private:
    struct object_creator
    {
        // This constructor does nothing more than ensure that instance()
        //  is called before main() begins, thus creating the static
        //  T object before multithreading race issues can come up.
        object_creator() { Singleton<T>::GetInst(); }
        inline void do_nothing() const {}
    };
    static object_creator create_object;

protected:
    ~Singleton() = default;
    Singleton() = default;

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

public:
    // If, at any point (in user code), Singleton<T>::instance()
    //  is called, then the following function is instantiated.
    static T& GetInst()
    {
        // This is the object that we return a reference to.
        // It is guaranteed to be created before main() begins because of
        //  the next line.
        static T obj;

        // The following line does nothing else than force the instantiation
        //  of Singleton<T>::create_object, whose constructor is
        //  called before main() begins.
        create_object.do_nothing();

        return obj;
    }
};
template <typename T>
typename Singleton<T>::object_creator Singleton<T>::create_object;
  • 删除拷贝构造函数和赋值运算符, 隐藏构造函数, 约束实例唯一.
  • 单例模板添加do_nothing函数调用, 保证单例实例构造调用在main调用之前.
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-12-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • singleton
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档