C ++删除静态数据 [英] C++ Deleting Static Data

查看:95
本文介绍了C ++删除静态数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含在堆上分配的,永远不变的私有静态数据的类,那么什么时候应该删除它(如果有的话)?

If I have a class that contains private static data allocated on the heap that never changes, when, if at all, should I delete it?

据我了解,类本身从未构造过(因为类不是C ++中的第一类对象),然后没有析构函数来删除其中的静态数据吗?我是C ++的新手,如果我对c ++的理解存在根本缺陷,或者答案很明显,对不起! 预先感谢,好吧.

As I understand it, a class itself is never constructed (because classes aren't first class objects in C++) then there is no destructor to delete the static data in? Im new at C++ so sorry if my understanding of c++ is fundamentaly flawed or if the answer is obvious! Thanks in advance, ell.

推荐答案

如果数据是静态的,则不会在堆上分配数据,而是将其分配给堆. 在关闭过程中被破坏了.

If the data is static, it isn't allocated on the heap, and it will be destructed during the shutdown of the process.

如果它是指向静态数据的指针,例如:

If it is a pointer to the data which is static, e.g.:

Something* MyClass::aPointer = new Something;

然后,像所有其他动态分配的数据一样,它只会 删除时销毁.有两种常见的解决方案:

then like all other dynamically allocated data, it will only be destructed when you delete it. There are two frequent solutions:

  • 使用一个智能指针,该指针具有一个将其删除的析构函数,或者

  • use a smart pointer, which has a destructor which deletes it, or

不要删除它;在大多数情况下,确实没有理由调用析构函数,并且如果您碰巧在其他静态对象的析构函数中使用实例,则会遇到破坏顺序的问题.

don't delete it; in most cases, there's really no reason to call the destructor, and if you happen to use the instance in the destructors of other static objects, you'll run into an order of destruction problem.

这篇关于C ++删除静态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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