Reason why not to have a DELETE macro for C++

前端 未结 12 1128
臣服心动
臣服心动 2020-11-29 07:01

Are there any good reasons (except \"macros are evil\", maybe) NOT to use the following macros ?

#define DELETE( ptr ) \\
i         


        
12条回答
  •  悲哀的现实
    2020-11-29 07:27

    Your macro fails for several reasons:

    • It is a macro. It doesn't respect scoping rules or a number of other language features, making it easy to use incorrectly.
    • It can cause compile-errors: DELETE (getPtr()); won't compile, because you can't set the function call to null. Or if the pointer is const, your macro will also fail.
    • It achieves nothing. delete NULL is allowed by the standard.

    Finally, as grimner said, you're trying to solve a problem that shouldn't exist in the first place. Why are you manually calling delete at all?` Don't you use the standard library containers? Smart pointers? Stack allocation? RAII?

    As Stroustrup has said before, the only way to avoid memory leaks is to avoid having to call delete.

提交回复
热议问题