简体   繁体   English

为什么我需要删除[]?

[英]Why do I need to delete[]?

Lets say I have a function like this: 让我们说我有这样的功能:

int main()
{
    char* str = new char[10];

    for(int i=0;i<5;i++)
    {
        //Do stuff with str
    }

    delete[] str;
    return 0;
}
  1. Why would I need to delete str if I am going to end the program anyways? 如果我要结束程序,为什么还需要删除str I wouldn't care if that memory goes to a land full of unicorns if I am just going to exit, right? 如果我要退出,我不在乎那个记忆是否会到达满是独角兽的土地,对吧?

  2. Is it just good practice? 这只是好习惯吗?

  3. Does it have deeper consequences? 它有更深的后果吗?

If in fact your question really is "I have this trivial program, is it OK that I don't free a few bytes before it exits?" 如果事实上你的问题确实是“我有这个琐碎的程序,那么在它退出之前我不会释放几个字节吗?” the answer is yes, that's fine. 答案是肯定的,那没关系。 On any modern operating system that's going to be just fine. 在任何现代操作系统上都会很好。 And the program is trivial; 该计划是微不足道的; it's not like you're going to be putting it into a pacemaker or running the braking systems of a Toyota Camry with this thing. 这并不是说你要把它放入心脏起搏器或用这个东西运行丰田凯美瑞的制动系统。 If the only customer is you then the only person you can possibly impact by being sloppy is you. 如果唯一的客户是你,那么你唯一可能因为草率而可能影响的人就是你。

The problem then comes in when you start to generalize to non-trivial cases from the answer to this question asked about a trivial case. 当你从这个问题的答案开始概括到非平凡的案例时,问题就出现了。

So let's instead ask two questions about some non-trivial cases. 因此,让我们提出两个关于一些非平凡案例的问题。

I have a long-running service that allocates and deallocates memory in complex ways, perhaps involving multiple allocators hitting multiple heaps. 我有一个长期运行的服务,以复杂的方式分配和释放内存,可能涉及多个分配器打多个堆。 Shutting down my service in the normal mode is a complicated and time-consuming process that involves ensuring that external state -- files, databases, etc -- are consistently shut down. 在正常模式下关闭我的服务是一个复杂且耗时的过程,涉及确保外部状态 - 文件,数据库等 - 始终关闭。 Should I ensure that every byte of memory that I allocated is deallocated before I shut down? 在关闭之前,我应该确保分配的每个内存字节都被释放吗?

Yes, and I'll tell you why. 是的,我会告诉你原因。 One of the worst things that can happen to a long-running service is if it accidentally leaks memory. 长期运行服务可能发生的最糟糕的事情之一就是它会意外泄漏内存。 Even tiny leaks can add up to huge leaks over time. 即使很小的泄漏也会随着时间的推移而增加大量泄漏。 A standard technique for finding and fixing memory leaks is to instrument the allocation heaps so that at shutdown time they log all the resources that were ever allocated without being freed. 查找和修复内存泄漏的标准技术是检测分配堆,以便在关闭时记录所有已分配但未释放的资源。 Unless you like chasing down a lot of false positives and spending a lot of time in the debugger, always free your memory even if doing so is not strictly speaking necessary. 除非你喜欢追逐大量误报并在调试器中花费大量时间,否则即使这样做并非严格必要,也要释放你的记忆

The user is already expecting that shutting the service down might take billions of nanoseconds so who cares if you cause a little extra pressure on the virtual allocator making sure that everything is cleaned up? 用户已经预计关闭服务可能需要数十亿纳秒,所以谁在乎你是否会对虚拟分配器造成一点额外的压力,确保一切都被清理干净? This is just the price you pay for big complicated software. 这只是您为大型复杂软件支付的价格。 And it's not like you're shutting down the service all the time, so again, who cares if its a few milliseconds slower than it could be? 并不是说你一直在关闭服务,所以再次,谁在乎它是否比它可能慢几毫秒?

I have that same long-running service. 我有同样长期运行的服务。 If I detect that one of my internal data structures is corrupt I wish to "fail fast". 如果我发现我的一个内部数据结构已损坏,我希望“快速失败”。 The program is in an undefined state, it is likely running with elevated privileges, and I am going to assume that if I detect corrupted state, it is because my service is actively being attacked by hostile parties. 该程序处于未定义状态,它可能以提升的权限运行,我将假设如果我检测到已损坏的状态,那是因为我的服务正在被敌对方主动攻击。 The safest thing to do is to shut down the service immediately. 最安全的做法是立即关闭服务。 I would rather allow the attackers to deny service to the clients than to risk the service staying up and compromising my users' data further. 我宁愿允许攻击者拒绝为客户提供服务,也不愿让服务熬夜并进一步损害我的用户数据。 In this emergency shutdown scenario should I make sure that every byte of memory I allocated is freed? 在这个紧急关闭场景中,我应该确保我分配的每个内存字节都被释放了吗?

Of course not. 当然不是。 The operating system is going to take care of that for you. 操作系统将为您处理。 If your heap is corrupt, the attackers may be hoping that you free memory as part of their exploit. 如果您的堆已损坏,攻击者可能希望您将内存作为其漏洞利用的一部分。 Every millisecond counts. 每毫秒都很重要。 And why would you bother polishing the doorknobs and mopping the kitchen before you drop a tactical nuke on the building? 为什么在你在建筑物上放置战术核武器之前,你还要打扰门把手和拖地厨房吗?

So the answer to the question "should I free memory before my program exits?" 所以问题的答案“我应该在程序退出之前释放内存吗?” is "it depends on what your program does". 是“这取决于你的程序做什么”。

Yes it is good practice. 是的,这是好习惯。 You should NEVER assume that your OS will take care of your memory deallocation, if you get into this habit, it will screw you later on. 你永远不应该假设你的操作系统会照顾你的内存释放,如果你养成这种习惯,它会在以后搞砸你。

To answer your question, however, upon exiting from the main, the OS frees all memory held by that process, so that includes any threads that you may have spawned or variables allocated. 但是,要回答您的问题,在退出main时,操作系统会释放该进程占用的所有内存,因此包括您可能生成的任何线程或分配的变量。 The OS will take care of freeing up that memory for others to use. 操作系统将负责释放内存以供其他人使用。

Important note : delete 's freeing of memory is almost just a side-effect. 重要提示: delete内存几乎只是一种副作用。 The important thing it does is to destruct the object. 它的重要作用是破坏对象。 With RAII designs, this could mean anything from closing files, freeing OS handles, terminating threads, or deleting temporary files. 使用RAII设计,这可能意味着关闭文件,释放操作系统句柄,终止线程或删除临时文件。

Some of these actions would be handled by the OS automatically when your process exits, but not all. 当您的进程退出时,操作系统会自动处理其中一些操作,但不是全部。

In your example, there's no reason NOT to call delete . 在您的示例中,没有理由不调用delete but there's no reason to call new either, so you can sidestep the issue this way. 但也没有理由要求new ,所以你可以这样回避问题。

char str[10];

Or, you can sidestep the delete (and the exception safety issues involved) by using smart pointers... 或者,您可以通过使用智能指针来回避删除(以及涉及的异常安全问题)...

So, generally you should always be making sure your object's lifetime is properly managed. 因此,通常您应该始终确保对象的生命周期得到妥善管理。

But it's not always easy: Workarounds for the static initialization order fiasco often mean that you have no choice but to rely on the OS cleaning up a handful of singleton-type objects for you. 但这并不总是那么容易: 静态初始化顺序惨败的变通方法通常意味着你别无选择,只能依靠操作系统为你清理一些单例类型的对象。

Contrary answer: No, it is a waste of time. 相反的答案:不,这是浪费时间。 A program with a vast amount of allocated data would have to touch nearly every page in order to return all of the allocations to the free list. 具有大量分配数据的程序几乎必须触及每个页面才能将所有分配返回到空闲列表。 This wastes CPU time, creates memory pressure for uninteresting data, and possibly even causes the process to swap pages back in from disk. 这会浪费CPU时间,为不感兴趣的数据创建内存压力,甚至可能导致进程从磁盘交换页面。 Simply exiting releases all of the memory back to the OS without any further action. 只需退出即可将所有内存释放回操作系统,无需任何进一步操作。

(not that I disagree with the reasons in "Yes", I just think there are arguments both ways) (不是我不同意“是”中的原因,我只是认为两种方式都存在争议)

Your Operating System should take care of the memory and clean it up when you exit your program, but it is in general good practice to free up any memory you have reserved. 退出程序时,您的操作系统应该处理内存并进行清理,但通常的做法是释放您保留的内存。 I think personally it is best to get into the correct mindset of doing so, as while you are doing simple programs, you are most likely doing so to learn. 我个人认为最好是进入这样做的正确心态,因为当你做简单的程序时,你很可能这样做是为了学习。

Either way, the only way to guaranteed that the memory is freed up is by doing so yourself. 无论哪种方式,保证释放内存的唯一方法就是自己动手。

new and delete are reserved keyword brothers. newdelete保留关键字兄弟。 They should cooperate with each other through a code block or through the parent object's lifecyle. 他们应该通过代码块或通过父对象的生命周期相互合作。 Whenever the younger brother commits a fault ( new ), the older brother will want to to clean ( delete ) it up. 每当弟弟犯错( new )时,哥哥就会想要清理( delete )它。 Then the mother (your program) will be happy and proud of them. 然后母亲(你的节目)将为他们感到高兴和自豪。

I cannot agree more to Eric Lippert's excellent advice: 我完全赞同Eric Lippert的出色建议:

So the answer to the question "should I free memory before my program exits?" 所以问题的答案“我应该在程序退出之前释放内存吗?” is "it depends on what your program does". 是“这取决于你的程序做什么”。

Other answers here have provided arguments for and against both, but the real crux of the matter is what your program does . 这里的其他答案提供了支持和反对两者的论据,但问题的真正关键在于您的计划所做的事情。 Consider a more non-trivial example wherein the type instance being dynamically allocated is an custom class and the class destructor performs some actions which produces side effect . 考虑一个更重要的例子,其中动态分配的类型实例是自定义类,类析构函数执行一些产生副作用的动作。 In such a situation the argument of memory leaks or not is trivial the more important problem is that failing to call delete on such a class instance will result in Undefined behavior. 在这种情况下,内存泄漏与否的争论是微不足道的,更重要的问题是未能在这样的类实例上调用delete将导致未定义的行为。

[basic.life] 3.8 Object lifetime [basic.life] 3.8对象生命周期
Para 4: 第4段:

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. 程序可以通过重用对象占用的存储来结束任何对象的生命周期,或者通过使用非平凡的析构函数显式调用类类型的对象的析构函数来结束任何对象的生命周期。 For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; 对于具有非平凡析构函数的类类型的对象,程序不需要在重用或释放对象占用的存储之前显式调用析构函数; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior. 但是, 如果没有对析构函数的显式调用或者如果没有使用delete-expression(5.3.5)来释放存储,则不应该隐式调用析构函数,并且任何依赖于析构函数生成的副作用的程序有未完成的行为。

So the answer to your question is as Eric says "depends on what your program does" 所以问题的答案就像埃里克所说“取决于你的程序做什么”

It's a fair question, and there are a few things to consider when answering: 这是一个公平的问题,在回答时需要考虑以下几点:

  • some objects have more complex destructors which don't just release memory when they're deleted. 某些对象具有更复杂的析构函数,这些析构函数在删除时不会释放内存。 They may have other side effects, which you don't want to skip. 他们可能有其他副作用,你不想跳过。
  • It is not guaranteed by the C++ standard that your memory will be released when the process terminates. C ++标准无法保证在进程终止时释放内存。 (Of course on a modern OS it will be freed, but if you were on some weird OS which didn't do that, you'd have to free your memory properly (当然在现代操作系统上它会被释放,但如果你在一些奇怪的操作系统上没有这样做,你必须正确地释放你的记忆
  • on the other hand, running destructors at program exit can actually take up quite a lot of time, and if all the do is release memory (which would be released anyway), then yes, it makes a lot of sense to just short-circuit that and exit immediately instead. 另一方面,在程序退出时运行析构函数实际上可能占用相当多的时间,如果所有的操作都是释放内存(无论如何都会释放),那么是的,短路是很有意义的然后立即退出。

Most operating systems will reclaim memory upon process exit. 大多数操作系统将在进程退出时回收内存。 Exceptions may include certain RTOS's, old mobile devices etc. 例外情况可能包括某些RTOS,旧移动设备等。

In an absolute sense your app won't leak memory; 绝对意义上,您的应用程序不会泄漏内存; however it's good practice to clean up memory you allocate even if you know it won't cause a real leak. 但是,即使您知道它不会导致真正的泄漏,清理您分配的内存也是一种很好的做法。 This issue is leaks are much, much harder to fix than not having them to begin with. 这个问题是泄漏很多,更难以解决而不是让它们开始。 Let's say you decide that you want to move the functionality in your main() to another function. 假设您决定要将main()中的功能移动到另一个功能。 You'll may end up with a real leak. 你最终可能会遇到真正的泄漏。

It's also bad aesthetics, many developers will look at the unfreed 'str' and feel slight nausea :( 这也是糟糕的美学,许多开发人员会看到不一致的'str'并感到轻微的恶心:(

You got a lot of professional experience answers. 你有很多专业经验的答案。 Here I'm telling a naive but an answer I considered as the fact. 在这里,我说的是一个天真的,但我认为是一个回答。

  • Summary 摘要

    3. Does it have deeper consequences? 3.它有更深的后果吗?

    A: Will answer in some detail. 答:会详细回答。

    2. Is it just good practice? 2.难道只是好的做法呢?

    A: It is considered a good practice. 答:这被认为是一种很好的做法。 Release resources/memory you've retrieved when you're sure about it no longer used. 当您确定不再使用它时,释放您检索到的资源/内存。

    1. Why would I need to delete str if I am going to end the program anyways? 如果我要结束程序,为什么还需要删除str
      I wouldn't care if that memory goes to a land full of unicorns if I am just going to exit, right? 如果我要退出,我不在乎那个记忆是否会到达满是独角兽的土地,对吧?

    A: You need or need not, in fact, you tell why. 答:你需要或者不需要,事实上, 告诉为什么。 There're some explanation follows. 下面有一些解释。

    I think it depends. 我认为这取决于。 Here are some assumed questions; 这是一些假设的问题; the term program may mean either an application or a function. 术语“ 程序”可以指应用程序或功能。

    Q: Does it depend on what the program does? 问:这取决于该计划的作用吗?

    A: If universe destroyed was acceptable, then no. 答:如果宇宙被摧毁是可以接受的,那么没有。 However, the program might not work correctly as expected, and even be a program that doesn't complete what it supposed to. 但是,程序可能无法按预期正常工作,甚至可能是一个无法完成预期的程序。 You might want to seriously think about why you build a program like this? 您可能想认真考虑为什么要构建这样的程序?

    Q: Does it depend on how the program is complicated? 问:这取决于程序的复杂程度吗?

    A: No. See Explanation. 答:不可以。见解释。

    Q: Does it depend on what the stability of the program is expected? 问:这取决于预期程序的稳定性吗?

    A: Closely. 答:关系密切。

    And I consider it depends on 我认为这取决于

    1. What's the universe of the program? 什么是程序的宇宙
    2. How's the expectation of the program that it done its work? 该计划的期望是如何完成其​​工作的?
    3. How much does the program care about others, and the universe where it is? 该计划对其他人及其所处的世界有多少关注?

      About the term universe , see Explanation. 关于术语Univers ,请参阅说明。

    For summary, it depends on what do you care about. 总结一下,这取决于在乎什么。


  • Explanation 说明

    Important: If we define the term program as a function, then its universe is application . 重要提示:如果我们将术语“ 程序”定义为函数,那么它的Universe就是应用程序 There are many details omitted; 省略了许多细节; as an idea for understanding, it's long enough, though. 作为理解的一个想法,它已经足够长了。

    We may ever seen this kind of diagram which illustrates the relationship between application software and system software. 我们可能已经看到过这种图表,它说明了应用软件和系统软件之间的关系。

    9RJKM.gif

    But for being aware the scope of which one covers, I'd suggest a reversed layout. 但是为了了解其涵盖范围,我建议采用相反的布局。 Since we are talking about software only, the hardware layer is omitted in following diagram. 由于我们仅讨论软件,因此下图中省略了硬件层。

    mjLai.jpg

    With this diagram, we realize that the OS covers the biggest scope, which is current the universe , sometimes we say the environment . 通过这个图,我们意识到操作系统涵盖了最大的范围,这是当前的宇宙 ,有时我们说环境 You may imagine that the whole achitecture consists of a lot of disks like the diagram, to be either a cylinder or torus(a ball is fine but difficult to imagine). 您可能会想象整个架构包含很多像图表一样的磁盘,无论是圆柱形还是圆环形(球很好但很难想象)。 Here I should mention that the outmost of OS is in fact a unibody , the runtime may be either single or multiple by different implemention. 在这里我要提到的是,最外层的OS实际上是一个整体 ,运行时可以是单个或多个不同的实现。

    It's important that the runtime is responsible to both OS and applications, but the latter is more critical. 运行时对OS和应用程序负责是很重要的,但后者更为关键。 Runtime is the universe of applications, if it's destroyed all applications run under it are gone. 运行时是应用程序的世界,如果它被销毁,则在其下运行的所有应用程序都将消失。

    Unlike human on the Earth, we live here, but we don't consist of Earth; 与地球上的人不同,我们住在这里,但我们不是由地球组成的; we will still live in other suitable environment if the time when the Earth are destroying and we weren't there. 如果地球正在摧毁而我们不在那里,我们仍将生活在其他合适的环境中。

    However, we can no longer exist when the universe is destroyed, because we are not only live in the universe, but also consist of the universe. 然而,当宇宙被摧毁时,我们就不复存在了,因为我们不仅生活在宇宙中,而且还包含宇宙。

    As mentioned above, the runtime is also responsible to the OS. 如上所述,运行时也对OS负责。 The left circle in the following diagram is what it may looks like. 下图中的左侧圆圈可能是它的样子。

    ScsZs.jpg

    This is mostly like a C program in the OS. 这大部分就像操作系统中的C程序。 When the relationship between an application and OS match this, is just the same situation as runtime in the OS above. 当应用程序和OS之间的关系与此匹配时,与上面的OS中的运行时情况相同。 In this diagram, the OS is the universe of applications. 在此图中,操作系统是应用程序的范围。 The reason of the applications here should be responsible to the OS, is that OS might not virtualize the code of them, or allowed to be crashed. 这里的应用程序的原因应该是对OS负责,OS可能不会虚拟化它们的代码,或者允许崩溃。 If OS are always prevent they to do so, then it's self-responsible, no matter what applications do. 如果操作系统总是阻止他们这样做,那么无论应用程序做什么,它都是自我负责的。 But think about the drivers , it's one of the scenarios that OS must allowed to be crashed, since this kind of applications are treated as part of OS . 但考虑一下驱动程序 ,它是操作系统必须允许崩溃的场景之一,因为这种应用程序被视为操作系统的一部分

    Finally, let's see the right circle in the diagram above. 最后,让我们在上图中看到正确的圆圈 In this case, the application itself be the universe. 在这种情况下,应用程序本身就是宇宙。 Sometimes, we call this kind of application operating system . 有时,我们称之为这种应用程序操作系统 If an OS never allowed custom code to be loaded and run, then it does all the things itself. 如果操作系统从不允许加载和运行自定义代码,那么它会自行完成所有操作。 Even it allowed, after itself is terminated, the memory goes nowhere but hardware . 即便它允许,在终止之后,内存无处可去,但硬件 All the deallocation that may be necessary, is before it was terminated. 所有可能需要的解除分配,都是在它终止之前。

    So, how much does your program care about the others? 那么,你的程序对其他程序的关注程度是多少? How much does it care about its universe? 它对宇宙的关注程度是多少? And how's the expectation of the program that it done its work? 该项目的期望是如何完成其​​工作的? It depends on what do you care about . 这取决于你在乎什么

Why would I need to delete str if I am going to end the program anyways? 如果我要结束程序,为什么还需要删除str?

Because you don't want to be lazy ... 因为你不想懒惰......

I wouldn't care if that memory goes to a land full of unicorns if I am just going to exit, right? 如果我要退出,我不在乎那个记忆是否会到达满是独角兽的土地,对吧?

Nope, I don't care about the land of unicorns either. 不,我也不关心独角兽的土地。 The Land of Arwen is a different matter, Then we could cut their horns off and put them to good use(I've heard its a good aphrodisiac). Arwen的土地是另一回事,然后我们可以削减它们的角度并使它们得到充分利用(我听说它是​​一种很好的壮阳药)。

Is it just good practice? 这只是好习惯吗?

It is justly a good practice. 这是一个很好的做法。

Does it have deeper consequences? 它有更深的后果吗?

Someone else has to clean up after you. 其他人必须在你之后清理。 Maybe you like that, I moved out from under my parents' roof many years ago. 也许你喜欢那样,多年前我从父母的屋檐下搬出去了。

Place a while(1) loop construct around your code without delete. 在代码周围放置while(1)循环结构而不删除。 The code-complexity does not matter. 代码复杂性并不重要。 Memory leaks are related to process time. 内存泄漏与处理时间有关。

From the perspective of debug, not releasing system resources(file handles, etc) can cause more significant and hard to find bugs. 从调试的角度来看, 不释放系统资源(文件句柄等)会导致更多重要且难以发现的错误。 Memory-leaks while important are typically much easier to diagnose( why can't I write to this file? ). 重要的内存泄漏通常更容易诊断( 为什么我不能写入此文件? )。 Bad style will become more of a problem if you start working with threads. 如果你开始使用线程,糟糕的风格将成为一个问题。

int main()
{

    while(1)
    { 
        char* str = new char[10];

        for(int i=0;i<5;i++)
        {
            //Do stuff with str
        }
    }

    delete[] str;
    return 0;
}

TECHNICALLY , a programmer shouldn't rely on the OS to do any thing. 技术上 ,程序员不应该依赖操作系统做任何事情。 The OS isn't required to reclaim lost memory in this fashion. 操作系统不需要以这种方式回收丢失的内存。

If you do write the code that deletes all your dynamically allocated memory, then you are future proofing the code and letting others use it in a larger project. 如果您确实编写了删除所有动态分配内存的代码,那么您将来可以验证代码并让其他人在更大的项目中使用它。

Source: Allocation and GC Myths (PostScript alert!) 来源: 分配和GC神话 (PostScript警报!)

Allocation Myth 4: Non-garbage-collected programs should always
deallocate all memory they allocate.

The Truth: Omitted deallocations in frequently executed code cause
growing leaks. They are rarely acceptable. but Programs that retain
most allocated memory until program exit often perform better without
any intervening deallocation. Malloc is much easier to implement if
there is no free.

In most cases, deallocating memory just before program exit is
pointless. The OS will reclaim it anyway. Free will touch and page in
the dead objects; the OS won't.

Consequence: Be careful with "leak detectors" that count allocations.
Some "leaks" are good!
  • I think it's a very poor practice to use malloc/new without calling free/delete. 我认为使用malloc / new而不调用free / delete是一种非常糟糕的做法。

  • If the memory's going to get reclaimed anyway, what harm can there be from explicitly deallocating when you need to? 如果内存无论如何都会被回收,那么在你需要的时候明确解除分配会有什么危害呢?

  • Maybe if the OS "reclaims" memory faster than free does then you'll see increased performance; 也许如果操作系统“回收”内存的速度比免费快,那么你会看到性能提升; this technique won't help you with any program that must remain running for any long period of time. 对于任何必须长时间保持运行的程序,此技术无法帮助您。

Having said that, so I'd recommend you use free/delete. 话虽如此,所以我建议你使用免费/删除。


If you get into this habit, who's to say that you won't one day accidentally apply this approach somewhere it matters? 如果你养成这种习惯,谁会说你有一天不会意外地在某个地方应用这种方法呢?


One should always deallocate resources after one is done with them, be it file handles/memory/mutexs. 在完成一个资源之后,应该总是释放资源,无论是文件句柄/内存/互斥锁。 By having that habit, one will not make that sort of mistake when building servers. 通过养成这种习惯,在构建服务器时不会犯这种错误。 Some servers are expected to run 24x7. 一些服务器预计将全天候运行。 In those cases, any leak of any sort means that your server will eventually run out of that resource and hang/crash in some way. 在这些情况下,任何类型的泄漏都意味着您的服务器最终会耗尽该资源并以某种方式挂起/崩溃。 A short utility program, ya a leak isn't that bad. 一个简短的实用程序,你的泄漏并不是那么糟糕。 Any server, any leak is death. 任何服务器,任何泄漏都是死亡。 Do yourself a favor. 帮自己一个忙。 Clean up after yourself. 自己清理干净。 It's a good habit. 这是一个好习惯。


Think about your class 'A' having to deconstruct. If you don't call
'delete' on 'a', that destructor won't get called. Usually, that won't
really matter if the process ends anyway. But what if the destructor
has to release e.g. objects in a database? Flush a cache to a logfile?
Write a memory cache back to disk? **You see, it's not just 'good
practice' to delete objects, in some situations it is required**.

Another reason that I haven't see mentioned yet is to keep the output of static and dynamic analyzer tools (eg valgrind or Coverity) cleaner and quieter. 我还没有提到的另一个原因是保持静态和动态分析仪工具(例如valgrind或Coverity)的输出更清洁和更安静。 Clean output with zero memory leaks or zero reported issues means that when a new one pops up it is easier to detect and fix. 清零输出,零内存泄漏或零报告问题意味着当弹出新内存时,更容易检测和修复。

You never know how your simple example will be used or evolved. 你永远不知道如何使用或演化你的简单例子。 Its better to start as clean and crisp as possible. 最好从干净和清爽开始。

Not to mention that if you are going to apply for a job as a C++ programmer there is a very good chance that you won't get past the interview because of the missing delete. 更不用说如果你要申请C ++程序员的工作,你很有可能因为缺少删除而无法通过面试。 First - programmers don't like any leaks usually (and the guy at the interview will be surely one of them) and second - most companies (all I worked in at least) have the "no-leak" policy. 首先 - 程序员通常不喜欢任何泄密(面试中的人肯定会是其中之一)而第二 - 大多数公司(我至少都在工作)都有“无泄漏”政策。 Generally, the software you write is supposed to run for quite a while, creating and destroying objects on the go. 通常,您编写的软件应该运行一段时间,在运行中创建和销毁对象。 In such an environment leaks can lead to disasters... 在这样的环境中,泄漏会导致灾难......

Instead of talking about this specific example i will talk about general cases, so generally it is important to explicitly call delete to de-allocate memory because (in case of C++) you may have some code in the destructor that you want to execute. 我不会谈论这个具体的例子,而是讨论一般情况,所以通常显式调用delete来取消分配内存是很重要的,因为(在C ++的情况下)你可能在析构函数中有一些你想要执行的代码。 Like maybe writing some data to a log file or sending shutting down signal to some other process etc. If you let the OS free your memory for you, your code in your destructor will not be executed. 就像可能将一些数据写入日志文件或将关闭信号发送到其他进程等。如果让操作系统为您释放内存,则析构函数中的代码将不会被执行。

On the other hand most operating systems will deallocate the memory when your program ends. 另一方面,大多数操作系统将在程序结束时释放内存。 But it is good practice to deallocate it yourself and like I gave destructor example above the OS won't call your destructor, which can create undesirable behavior in certain cases! 但是好的做法是自己解除分配,就像我在操作系统上面给出析构函数示例一样,不会调用你的析构函数,这会在某些情况下造成不良行为!

I personally consider it bad practice to rely on OS to free your memory (even though it will do) the reason is if later on you have to integrate your code with a larger program you will spend hours to track down and fix memory leaks! 我个人认为依靠操作系统释放你的内存是不好的做法(即使它会这样做),原因是如果你以后必须将你的代码与更大的程序集成,你将花费数小时来追踪和修复内存泄漏!

So clean your room before leaving! 所以在离开之前打扫房间!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM