引子
- 早期c++编程中定义空指针我们会使用NULL,如下:
int *p = NULL;
#include <iostream>
#include <string>
using namespace std;
void func(int* num){
cout << "this is the ptr function..." << endl;
}
void func(int num){
cout << "this is the normal function..." << endl;
}
int main(int argc, char** argv){
func(NULL);
return 0;
}
- g++ 4.8.4编译以上程序会直接报错,错误信息如下:
test.cpp: In function ‘int main(int, char**)’:
test.cpp:15:15: error: call of overloaded ‘func(NULL)’ is ambiguous
func(NULL);
^
test.cpp:15:15: note: candidates are:
test.cpp:6:6: note: void func(int*)
void func(int* num){
^
test.cpp:10:6: note: void func(int)
void func(int num){
^
原因
#define NULL (void *)0
- 编译器编译以上示例代码时,NULL会被直接替换成(void *)0,既可以转成为指针类型也可以转换成int类型,因此结果不确定。
解决
- c++11重新定义了空指针:nullptr,不能被转换成数字。
- 如果没有使用到指针类型的函数重载,使用NULL也不会报错,但是为了养成好习惯,使用nullptr。
注意项
- nullptr 需要c++ 11 支持,编译时需要加上 -std=c++11 例如:
g++ nullptr_test.cpp -std=c++11 -o test