在什么情况下,单例设计模式可以生成同一单例类的多个实例? [英] In what cases, a singleton design pattern may generate multiple instances of the same singleton class?

查看:205
本文介绍了在什么情况下,单例设计模式可以生成同一单例类的多个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个面试问题。


在C ++中,对于单例设计模式,可能有
多个类的实例吗?如果是,在什么情况下?

In C++, for singleton design pattern, is it possible that there may be multiple instances of the class? If yes, in what cases?

我的想法:

情况下,没有同步保护,可能我们可能有多个实例由多个线程生成。

In multithreading cases, without synchronous protections, it is possible that we may have multiple instances generated by multiple threads.

我们可以使用互斥来做保护。例如,使用互斥保护全局变量作为计数器,以保留实例数,以确保只有一个实例。

We can use a mutex to do the protection. For example, use a mutex to protect a global variable as counter to keep the numbers of instances to assure that there is only one instance.

任何更好的想法?

推荐答案

是一个新的工具,使一次性的初始化可靠 - std :: call_once 。您可以在此处找到一个很好的参考。如果你使用支持C ++ 11的编译器,这给你一个不错的平台无关,标准的方法来完成它。

In C++11 there is a new facility to make once-only initialization reliable - std::call_once. You can find a good reference for it here. If you're working with a compiler that supports C++11, this gives you a nice platform-independent, standard way of accomplishing it.

在平台的依赖级别上,大多数操作系统提供了一次性初始化的方法。例如。在iOS或OS X中,您可以使用 dispatch_once /Reference/reference.htmlrel =nofollow> Grand Central Dispatch 。在Windows上,有一个 One-时间初始化API 在Vista及更高版本中可用。

At the platform dependent level, most operating systems provide a means of doing once-only initialization. E.g. in iOS or OS X you can use dispatch_once from Grand Central Dispatch. On Windows, there's a One-Time Initialization API available in Vista and later.

这些是很好的,当你没有一个标准的选择,但由于C ++ 11,你不再需要在平台上做这样的事情 - 依赖方式。它非常适合单例初始化。

Those are nice when you don't have a standard alternative, but thanks to C++11, you no longer need to do that sort of thing in a platform-dependent manner. It's perfect for singleton initialization.

这篇关于在什么情况下,单例设计模式可以生成同一单例类的多个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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