25

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!

1 Answer 1

30

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).

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.