23

I am refactoring some older code that uses NULL in many places. The question is

Is it safe to blindly replace all NULL instances by nullptr?

I am particularly interested in scenario where replacing NULL by nullptr may lead to some run-time errors (compile-time errors would be ok) but I can't think of any. If not, would it be safe to just auto-replace NULL by nullptr (fixing compile time errors if any).

I apologize if question have been asked earlier - I couldn't find it, I will delete it if you point me to the answer!

T.C.
  • 133,968
  • 17
  • 288
  • 421
Ilya Kobelevskiy
  • 5,245
  • 4
  • 24
  • 41

1 Answers1

28

In practice it should be fairly safe.

But, technically, it is possible that the meaning of your program changes, without causing any compiler errors. Consider the following program:

void foo(int) { std::cout << "int\n"; }
void foo(int*) { std::cout << "int*\n"; }

int main() {
    foo(NULL);       // prints 'int'
    foo(nullptr);    // prints 'int*'
    return 0;
}

Note that when there's ambiguity between an int and a pointer when passing NULL, the pointer version is what's almost always desired -- which means that most real programs won't have an ambiguity like that in the first place (or will use casts like (int*)NULL to get around it, in which case replacement by nullptr is perfectly fine).

Cameron
  • 96,106
  • 25
  • 196
  • 225
  • 6
    Worth noting that a C++11 compiler *could* legally define `NULL` as `nullptr`, though in practice none does because it would break too much existing code with people writing crazy stuff like `char c = NULL;` and the like. – T.C. Sep 16 '14 at 23:19