About the usage of new and delete, and Stroustrup's advice

前端 未结 3 604
旧时难觅i
旧时难觅i 2021-02-01 03:32

About the usage of new and delete, and Stroustrup\'s advice...

He says something like (but not exactly, this is from my notes of his book):

A rule

3条回答
  •  深忆病人
    2021-02-01 04:09

    The way I think of it is that every resource should be owned by something. The owner is the one who is responsible for cleaning up. Usually this owner is a smart pointer of some kind, but even std::vector is an owner a resource: the block of memory which stores it's contiguous elements. This advice holds not just for memory but any resource such as file descriptors, database handles, mutexes, etc...

    When you call new and delete manually in some part of your code that's not a wrapper class, you the programmer become the resource owner. With ownership comes the responsibility of cleaning up after yourself. Now you and all of the maintenance programmers who come after you have to ensure that all code paths after the new eventually lead to a delete. Even for simple functions this very is easy to get wrong. With exceptions, almost impossible unless you carefully wrap everything in try catch blocks, resulting runtime performance penalties and polluting your code with extra scopes and unnecessary exception logic. Finally, even if you do get it right, you just wasted a lot your time doing this tedious work of resource management. The compiler is tool which can do this work for you, use it.

    The worst situation is when some subsystem allocates a resource, it gets passed around the application, and some other far away subsystem frees it. The number of possible code paths in this situation is intractable. It is very difficult if not impossible for a human being to reason about and trust. In my opinion, this style of programming is unmaintainable. How many C projects have you worked with in the past that are riddled with memory errors, especially on rarely if never executed error handling paths? I've dealt with more than I care to see anymore.

    C has manual memory management, Java and others have garbage collection. C++ has RAII. It's as efficient as C and and almost as safe as garbage collection.

    My rule is simple, if you find yourself manually cleaning up any resource, you have just written a bug.

提交回复
热议问题