使用析构函数作为私有的是什么? [英] What is the use of having destructor as private?

查看:160
本文介绍了使用析构函数作为私有的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用析构函数作为私有的是什么?

What is the use of having destructor as private?

推荐答案

基本上,任何时候你想要一些其他类负责对于类的对象的生命周期,或者你有理由阻止对象的销毁,你可以使析构函数私有。

Basically, any time you want some other class to be responsible for the life cycle of your class' objects, or you have reason to prevent the destruction of an object, you can make the destructor private.

例如,做一些类型的引用计数事情,你可以有对象(或经理已经朋友ed)负责计数引用自身的数量,并在数量达到零时删除它。

For instance, if you're doing some sort of reference counting thing, you can have the object (or manager that has been "friend"ed) responsible for counting the number of references to itself and delete it when the number hits zero. A private dtor would prevent anybody else from deleting it when there were still references to it.

对于另一个实例,如果你有一个对象有一个管理器(或自身),可能会破坏它或可能会拒绝破坏它取决于程序中的其他条件,如数据库连接正在打开或正在写入文件。你可以在类或管理器中有一个request_delete方法,它将检查该条件,它将删除或拒绝,并返回一个状态告诉你它做了什么。这更灵活,只是调用删除。

For another instance, what if you have an object that has a manager (or itself) that may destroy it or may decline to destroy it depending on other conditions in the program, such as a database connection being open or a file being written. You could have a "request_delete" method in the class or the manager that will check that condition and it will either delete or decline, and return a status telling you what it did. That's far more flexible that just calling "delete".

这篇关于使用析构函数作为私有的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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