简体   繁体   中英

Pointer negation in C++ (!ptr == NULL)

I have come across the following null check for a pointer ptr

if(!ptr == NULL){
delete ptr;
ptr = NULL;
}

Now, apart from using NULL instead of the favored nullptr , I wonder if this code makes sense and is guaranteed to work by the implications of C++ standard.

Checking with msvc debugger, it does what it is supposed to do, ie execute the deletion only when ptr is different from NULL . But I seem fail to see why this can work when

if(ptr){...}

will work as well.

This is badly written code. Both GCC and clang emits a warning for it. Unfortunately, MSVC doesn't.

In the expression, !ptr == NULL , !ptr will evaluate true or false (a bool value!) depending on ptr is nullptr or not.

Then this bool value is compared to NULL , which is an implementation defined null pointer constant (its usage is discouraged, as we have nullptr now). The NULL will be converted to bool (becomes false ). This false value is compared to the bool which comes from !ptr . This comparison happens to do expected thing.

But, presumably, the comparison is not intended this way.

The correct version could be if (!(ptr==NULL)) . Or if (ptr!=NULL) . Or your simple version, if (ptr) .

Note, that the comparison is unnecessary (as delete handles nullptr pointers), so the code could be simply:

delete ptr;
ptr = nullptr;

This is an operator precedence problem.

== has a lower precedence than ! , so your conditional gets parsed as (!ptr) == NULL , not !(ptr == NULL) .

That roughly results in (ptr != NULL) == NULL , or !(ptr) , which is the exact opposite of what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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