Calling delete on NULL pointers - C++03 vs C++11

后端 未结 2 823
北海茫月
北海茫月 2020-12-03 17:27

In the C++03 Standard, I see:

5.3.5 Delete

2 If the operand has a class type, the operand is converted to a pointer type by calli

相关标签:
2条回答
  • 2020-12-03 17:46

    It looks like we can find a rationale for this change in defect report 348, which says:

    Specifically, standard says in 5.3.5 [expr.delete] paragraph 2:

    ...if the value of the operand of delete is the null pointer the operation has no effect.

    Standard doesn't specify term "has no effect". It is not clear from this context, whether the called deallocation function is required to have no effect, or delete-expression shall not call the deallocation function.

    Furthermore, in para 4 standard says on default deallocation function:

    If the delete-expression calls the implementation deallocation function (3.7.4.2 [basic.stc.dynamic.deallocation]), if the operand of the delete expression is not the null pointer constant, ...

    Why it is so specific on interaction of default deallocation function and delete-expr?

    If "has no effect" is a requirement to the deallocation function, then it should be stated in 3.7.4.2 [basic.stc.dynamic.deallocation], or in 18.6.1.1 [new.delete.single] and 18.6.1.2 [new.delete.array], and it should be stated explicitly.

    part of the resolution was the change in wording that you noted, although the language around that phrasing has changed quite a bit but the logic of getting rid of the has no effect language still stands, it is not a well defined term and so should be replaced with well specified language.

    0 讨论(0)
  • 2020-12-03 17:51

    The latest C++14 draft (N3797) has roughly equivalent wording in this section. But the behaviour is equally-strongly specified, just not in quite the same paragraph.

    If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2 ).

    If the value of the operand of the delete-expression is not a null pointer value, then: — If the allocation call for the new-expression for the object to be deleted was not omitted ( 5.3.4 ), the delete-expression shall call a deallocation function ( 3.7.4.2 ). The value returned from the allocation call of the new-expression shall be passed as the first argument to the deallocation function. — Otherwise, the delete-expression will not call a deallocation function ( 3.7.4.2 ).

    These paragraphs are clearly just as strong as C++03. The Committee could not have broken the behaviour of programs which delete null pointers, as these are widespread and the cost of fixing would be much too large. It would have made C++11 unimplementable.

    0 讨论(0)
提交回复
热议问题