C++ 单例设计模式 [英] C++ Singleton design pattern

查看:27
本文介绍了C++ 单例设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我遇到了 C++ 单例设计模式的实现/实现.它看起来像这样(我从现实生活中采用了它):

Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):

// a lot of methods are omitted here
class Singleton
{
   public:
       static Singleton* getInstance( );
       ~Singleton( );
   private:
       Singleton( );
       static Singleton* instance;
};

从这个声明中,我可以推断出实例字段是在堆上启动的.这意味着存在内存分配.对我来说完全不清楚的是内存何时会被释放?或者是否存在错误和内存泄漏?好像是实现有问题.

From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.

我的主要问题是,我如何以正确的方式实施它?

My main question is, how do I implement it in the right way?

推荐答案

在 2008 年,我提供了单例设计模式的 C++98 实现,它是惰性求值、保证破坏、非技术线程安全的:
谁能给我一个C++ 中的 Singleton 示例?

In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
Can any one provide me a sample of Singleton in c++?

这里是单例设计模式的更新的 C++11 实现,它经过延迟评估、正确销毁和 线程-安全.

Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        S() {}                    // Constructor? (the {} brackets) are needed here.

        // C++ 03
        // ========
        // Don't forget to declare these two. You want to make sure they
        // are inaccessible(especially from outside), otherwise, you may accidentally get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement

        // C++ 11
        // =======
        // We can use the better technique of deleting the methods
        // we don't want.
    public:
        S(S const&)               = delete;
        void operator=(S 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:应该如何使用

See this article about when to use a singleton: (not often)
Singleton: How should it be used

看这两篇关于初始化顺序和如何应对的文章:
静态变量初始化顺序
查找C++静态初始化顺序问题

See this two article about initialization order and how to cope:
Static variables initialisation order
Finding C++ static initialization order problems

请参阅这篇描述生命周期的文章:
静态变量在C++ 函数?

See this article describing lifetimes:
What is the lifetime of a static variable in a C++ function?

请参阅这篇文章,该文章讨论了对单例的一些线程影响:
单例实例声明为 GetInstance 方法的静态变量,它是线程安全的吗?

See this article that discusses some threading implications to singletons:
Singleton instance declared as static variable of GetInstance method, is it thread-safe?

请参阅这篇解释为什么双重检查锁定在 C++ 上不起作用的文章:
什么是C++ 程序员应该知道的所有常见的未定义行为?
多布斯博士:C++ 和双重风险-检查锁定:第一部分

See this article that explains why double checked locking will not work on C++:
What are all the common undefined behaviours that a C++ programmer should know about?
Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I

这篇关于C++ 单例设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆