Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When NULL cannot be replaced by nullptr?

Tags:

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!

like image 877
Ilya Kobelevskiy Avatar asked Sep 16 '14 19:09

Ilya Kobelevskiy


1 Answers

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

like image 81
Cameron Avatar answered Oct 26 '22 15:10

Cameron