I know using nullptr
is more "typed". It can distinguish pointer type
and 0
and works well in function overloading and template specialization.
So I am not sure whether it is safe to replace the NULL
to nullptr
in my old Win32 project in every HANDLE
/HWND
/HINSTNACE
initialization usages?
Any suggestion will be helpful. Thanks
nullptr is a good value to initialize, to indicate that there is no memory pointed to by the pointer. Also, delete operation on nullptr is safe, whereas delete on arbitrary values (which is typically the case when you don't initialize the pointer) can cause Segmentation faults.
Setting pointers to NULL following delete is not universal good practice in C++. There are times when it is a good thing to do, and times when it is pointless and can hide errors. There are plenty of circumstances where it wouldn't help. But in my experience, it can't hurt.
The nullptr keyword represents a null pointer value. Use a null pointer value to indicate that an object handle, interior pointer, or native pointer type does not point to an object.
nullptr is a new keyword introduced in C++11. nullptr is meant as a replacement to NULL . nullptr provides a typesafe pointer value representing an empty (null) pointer. The general rule of thumb that I recommend is that you should start using nullptr whenever you would have used NULL in the past.
For handles that resolve to a pointer type you can use nullptr
instead of NULL
. A good number of handle types are typedef
'd as pointers so you shouldn't run into much problem.
This does not mean it is ok to use either NULL
or nullptr
. Some calls return INVALID_HANDLE_VALUE
which in VS2013 is defined as ((HANDLE)(LONG_PTR)-1)
and relying on a null value to indicate an invalid/unopen handle may cause problems. For instance CreateFile
returns INVALID_HANDLE_VALUE
instead of a zero or null value. All places in your code that assumes a null value indicates an unopened handle may cause problems.
Yes. HWND, HANDLE, etc., most resolve to void *
, so there's no reason not to use nullptr
. That being said, it may be deemed more consistent with the API to use NULL
, but it will not make a difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With