Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

nullptr

Use case

Unambiguous null checks when functions are overloaded.

Explanation

NULL is just 0, so the compiler cannot choose between uint64_t and const char *. nullptr has type std::nullpts_t which only converts to pointers. This makes the call unambiguous.

Code

#include <cstdint>
#include <iostream>

void analyze(uint64_t addr) {
  std::cout << "Analyzing address: 0x" << std::hex << addr << "\n";
}

void analyze(const char *symbol) {
  if (symbol) {
    std::cout << "Analyzing symbol: " << symbol << "\n";
  } else {
    std::cout << "Analyzing symbol: (null)\n";
  }
}

int main() {
  analyze(0x10001000);
  analyze("_main");

  // more than one instance of overloaded function "analyze" matches the
  // argument list
  // function "analyze(uint64_t addr)"
  // function "analyze(const char *symbol)"
  // analyze(NULL);
  analyze(nullptr);

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/nullptr
Analyzing address: 0x10001000
Analyzing symbol: _main
Analyzing symbol: (null)