There are three ways (that I'm aware of) to initialize a pointer to a null value :
T a = T(); // T is a pointer type
T a{}; // brace initializers don't suffer from the most vexing parse
Even though a typedef is required, this form is met in non generic code as well, eg
typedef int* ip;
int *p = ip();
nullptr manuallyint *p = nullptr;
int *p = NULL;
What are the pros and cons of each method ?
Are there uses case where each method is considered best fitting?
Stroustroup always told us to us to us
TYPE *var = 0 ;
In ye olde days of C++ there was little standardization of libraries. Doing
TYPE *var = NULL ;
would often give different results when the definition of NULL was not standardized. Some compilers picked up the C definition.
C++ needed
#define NULL (0)
to work right while C headers generally had
#define NULL ((void*)0)
Thus, 0 became the accepted method for setting null pointers.
With the standard changes, there might be a shift to nullptr.
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