Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

c++ - Is it undefined behaviour to delete a null void* pointer?

I know that deleteing a null pointer is a no-op:

In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.
(C++ Standard 5.3.5 [expr.delete] p2)

And also that deleting a void* pointer is undefined behaviour because the destructor can't be called as there are no objects of type void:

In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object representing a base class of such an object. If not, the behavior is undefined.
(C++ Standard 5.3.5 [expr.delete] p2)

Now, normally I take it that things that are listed first overrule things that are listed later on, but what about null void* pointer as the following?

void* p = 0;
delete p; // UB or well-defined?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wonder how you can reach up a situation where you are deleting a pointer only if it is null. But staying in language lawyering mode...

In C++ 03

5.3.5/1

the operand of delete shall have a pointer type or a class type having a single conversion to a pointer type.

void* is a pointer type so a null void pointer meets the static requirement.

5.3.5/2

In either alternative [delete and delete[]], if the value of the operand of delete is the null pointer the operation has no effect.

And this gives the wanted behavior.

5.3.5/3

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined.

This is not relevant, a null pointer doesn't reference an object on which to check the additional constraint.

In C++ 0X

5.3.5/1

The operand shall have a pointer to object type, or a class type having a single non-explicit conversion function (12.3.2) to a pointer to object type.

void* isn't a pointer to object type, so should be rejected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...