Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ - how do I disable implicit conversion from 0 to pointer types?

Tags:

c++

g++

Specifically, I want the following code to fail:

void a(void*){}
int main(){
    a(0); // FAIL
    a(NULL); // FAIL
    a(nullptr); // success
}

And I want the following code to compile:

void a(int){}
void a(void*){}
int main(){
    a(0); // calls first a
    a(NULL); // calls first a; that's why I have -Werror
    a(nullptr); // calls second a
}

The following code does not compile currently, but should according to my rule:

void a(std::size_t){}
void a(void*){}
int main(){
    a(0); // two candidates
}

Any idea how to make g++ behave like that?

like image 573
Hristo Venev Avatar asked Oct 20 '25 04:10

Hristo Venev


1 Answers

You can compile with -Wzero-as-null-pointer-constant to get a warning when you use 0 or NULL instead of nullptr. To promote that to an error, I believe using -Werror=zero-as-null-pointer-constant would work.

Unfortunately, this is simply a warning and is not able to change overload resolution rules. I also believe NULL must be defined as 0 rather than nullptr in order for the warning to catch it, but at least as of GCC 4.9, std::is_null_pointer<decltype(NULL)>::value is false and GCC warns when using NULL.

like image 78
chris Avatar answered Oct 22 '25 17:10

chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!