General features: nullptr

code

Syntax

Usage / Usability

  • This feature is introduced mainly to take care of the pitfalls generated by using the (infamous and nasty) NULL macro. NULL is nothing but a preprocessor expanding to 0 at compile time and this expansion often leads to ambiguity.

Given the following functions, how can we call the function cast with a null pointer?

C++03:

NULL vs nullptr

  • nullptr can be used at all places where NULL is expected
  • nullptr is convertible to bool
  • Like NULL, nullptr is implicitly convertible and comparable to any pointer type
  • Unlike NULL, it is not implicitly convertible or comparable to integral types

 

Interaction with templates

  • Without templates

Given the following functions

all calls below are valid

  • With templates (forwarding templates)

We cannot forward int* as 0 or NULL in templates!

 

PROS and CONS

PROS

  • no more int vs pointer type (eg. char*)
  • Can be used in templates

CONS

  • If you already used nullptr as a variable / class name prior to C11, your code will no longer compile, so you will need to edit your sources and rename it.

 

QUIZ – What functions will be called?

Given the following functions (one with null_ptr and a templated one)

Which functions will be called in all cases?

Answer:

1 and 2 will call the first (templated) function: the parameter is still of type int*, no matter what is it pointing to. the 3rd function will call the foo function with param of type nullptr_t.

Leave a comment

Your email address will not be published.