I am refactoring some older code that uses NULL
in many places. The question is
Is it safe to blindly replace all
NULL
instances bynullptr
?
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!
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With