破坏单例对象 [英] destroying a singleton object

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

问题描述

销毁单例对象的最佳方法是什么?

What is the best way to destroy a singleton object?

案例A:单线程环境

案例B:多线程环境

case A: Single threaded Environment
case B: Multi Threaded Environment

示例片段(如果有)将是真正有用的。

Sample snippets(if any) will be really helpful.

我没有一个特定的用例我只是想了解,如果在所有单身人士必须使用如何正确销毁它。根据我的理解,从注释,有两种情况可能:

1.当没有代码访问它时,销毁单例(使用智能指针,它将使用RAII自己消灭对象)

2.退出程序时销毁单例程序,无论某个代码是否持有单例。
(通过在main退出之前删除实例来显式删除)

I don't have a specific use case I am just trying to understand that IF AT ALL the singleton has to be used how to destroy it correctly. As i understand, from the comments, there are 2 scenarios possible:
1. Destroy the singleton when no code is accessing it.(use smart pointers which will take care of destroying the object by itself using RAII)
2. Destroy a singleton when exiting the program irrespective of whether or not some code was holding on to the singleton. (explicitly destroy by deleting the instance just before main exits)

推荐答案

真的,我强烈建议您重新考虑您对单例的选择,特别是在多线程环境中。。

Don't create it in the first place!

而是只需在 main()中创建一个实例,并将其传递到需要调用的层次结构。

Seriously, I strongly recommend you reconsider your choice of singleton, especially in a multithreaded environment. Instead just create an instance in main() and pass it down the call hierarchy to where it is needed.

您可以使用类似 shared_ptr 的方法确保对象停留在周围,直到没有人需要它。

You can use something like shared_ptr to ensure that the object stays around until no-one needs it any more.

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

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