Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to initialize MS HANDLE to nullptr?

Tags:

c++

winapi

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

like image 273
Chen OT Avatar asked Apr 23 '14 02:04

Chen OT


People also ask

Should I initialize a pointer to nullptr?

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.

Do you need to set nullptr after delete?

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.

What does nullptr mean?

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.

Is nullptr the same as null?

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.


2 Answers

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.

like image 90
Captain Obvlious Avatar answered Sep 25 '22 00:09

Captain Obvlious


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.

like image 40
smiling_nameless Avatar answered Sep 25 '22 00:09

smiling_nameless