我必须在 C++ 中进行垃圾收集吗?析构函数
我正在编写一个 C++ 析构函数(我希望这是正确的术语;我是 C++ 新手),并且我对垃圾收集到底需要什么并不肯定。假设我有 2 个指针作为实例变量,我需要对它们进行垃圾收集吗?如果我有一个对象作为实例变量怎么办?还是指向对象的指针?
我只是对到底需要删除什么以及自动清理什么有点模糊。
谢谢
I'm writing a C++ destructor (I hope that's the right term; I'm new to C++) and I'm not positive on what exactly I need to garbage collect. Let's say I have 2 pointers as instance variables do I need to garbage collect them? What about if I have an object as an instance variable? Or a pointer to an object?
I'm just a little fuzzy on what exactly needs to be deleted and what is automatically cleaned up.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
一般经验法则是...如果您调用
new
,请调用delete
。如果您调用了new[]
,请调用delete[]
。如果您在类外部访问这些指针并有效地共享它们,那么您需要小心“拥有”对象在共享对象仍在使用时删除
。垃圾收集这个词不太合适。您想要销毁
该对象并释放
其内存。这就是delete
/delete[]
的作用。new
/new[]
分配内存并构造
一个对象。在C++中,没有垃圾收集器。您必须“手动”处理它。这并不是说这一切都很乏味。您可能会开始使用智能指针来为您处理一些此类逻辑。有关详细信息,请参阅此问题。
General rule of thumb is... if you called
new
, calldelete
. If you callednew[]
, calldelete[]
. If you're accessing these pointers outside of the class and effectively sharing them, you'll want to be careful about the "owning" objectdelete
ing the shared objects while they're still in use. Garbage collection isn't quite the right term. You want todestroy
the object andfree
its memory. This is whatdelete
/delete[]
does.new
/new[]
allocate memory andconstruct
an object.In C++, there is no garbage collector. You must "manually" handle it. That's not to say that it's all tedium. You'll probably get into using smart pointers to handle some of this logic for you. See this question for more information.
您必须
删除
使用new
分配的每个指针。就是这么简单,又这么复杂;在删除
之前,您不得丢失由new
分配的任何指针。另外,您需要确保如果您使用 new[] 来分配指针,则调用delete[] 来释放它。
这与类实例中碰巧有什么指针无关。您需要知道谁拥有它们(所有者是负责删除它们的人)。如果您的对象拥有这些指针,那么它应该删除它们。如果它不拥有它们,那么它就不应该拥有它们。
这也是经验丰富的 C++ 程序员尽可能避免使用裸指针的原因。智能指针允许您在语言中按语义表达所有权类型。这样,您就不必跟踪谁拥有什么;您只需知道谁拥有什么。您可以通过所使用的智能指针的类型知道谁拥有它。
You must
delete
every pointer you allocate withnew
. It's that simple, and it's that complicated; you must not lose track of any pointer allocated bynew
until you havedelete
d it.Also, you need to make sure that if you use
new[]
to allocate a pointer, you calldelete[]
to deallocate it.It's not about what pointers you happen to have in a class instance. You need to know who owns them (the owner is the one responsible for deleting them). If your object owns those pointers, then it should delete them. If it doesn't own them, then it shouldn't.
This is also why experienced C++ programmers avoid naked pointers where possible. Smart pointers allow you to express ownership types semantically in the language. That way, you don't have to keep track of who owns what; you know who owns it by the type of smart pointer being used.
您必须对使用
new
创建的每个空间调用delete
,对使用new[]
创建的每个区域调用delete[]
>,以及使用malloc
获得的所有内容的free
。您还应该关闭您打开的所有套接字,并清除您的类拥有的任何其他操作系统资源。
注意:这不称为垃圾收集。垃圾收集是指此过程作为库或语言运行时的一部分自动发生,而不是当您显式执行时。
You must call
delete
on every space you created usingnew
,delete[]
on every area created usingnew[]
, andfree
on everything you got usingmalloc
.You should also close any sockets you opened, and clear up any other OS resources your class owns.
Note: this is not called garbage collection. Garbage collection is when this process happens automatically, as part of a library or language runtime, not when you do it explicitly.
您应该首先了解“资源获取即初始化”(RAII) 和智能指针(
shared_ptr
和unique_ptr
)。这是如果你来自其他语言,你必须了解 C++ 中的习惯用法。通常的做法是,您在构造函数中分配的任何内容都必须在析构函数中释放(请参阅其他答案以了解如何操作)。事件更好,尝试尽可能多地使用值并尽可能少地使用
new
。C++ 喜欢堆栈,堆栈分配和释放是自动且廉价的(无需新建,无需删除)。使用引用和常量引用而不是指针。
如果您确实需要动态内存,请尝试使用智能指针之一。
You should start by learning about "Resource Acquisition is Initialization" (RAII) and smart pointers (
shared_ptr
andunique_ptr
). This is the idiom you have to know in C++ if you come from other languages.Usual practice says that whatever you allocated in your constructor must be deallocated in your destructor (see other answers to know how). Event better, try to use values as much as possible and
new
as less as possible.C++ loves the stack, and stack allocation and deallocation are automatic and cheap (no new, no delete). Use references and const-references instead of pointers.
If you really need dynamic memory, try to use one of the smart pointers.
使用 new 运算符分配的任何内存都需要释放。
您可以通过执行以下操作来分配内存:
并通过执行以下操作来删除内存:
如果您正在使用类,则需要在构造函数(分配)和析构函数(释放)中执行相同的操作。
Any memory you allocate using new operator needs to be freed.
You allocate memory by doing:
and you delete it by doing:
If you are playing with Classes, you need to do the same thing in constructors (allocate) and destructors (deallocate).
在理想的世界里,什么都没有。每种模式都有智能指针和容器。有时,您必须编写自己的实现,或增强现有的实现,但您需要的大部分内容已经存在。
对于数组,从
std::array
和std::vector
开始。对于对象,请阅读智能指针和共享指针。一般来说:如果您需要调用delete
、delete[]
或free
,您通常会向下调用错误的道路。In an ideal world, nothing. There are smart pointers and containers for every pattern. Sometimes, you will have to write your own, or augment existing implementations, but much of what you need exists already.
For an array, start with
std::array
andstd::vector
. For objects, read up on smart pointers and shared pointers. As a generalization: if you need to calldelete
,delete[]
orfree
, you have usually headed down the wrong path.您需要对不再需要的所有指针进行垃圾收集。否则你就会遇到悬空指针问题。
You need to garbage collect all pointers that you don't no longer need. Otherwise you would have the dangling pointer problem.