在工作中,避免产生“野指针”最有效的方法,是以下两点:
1. 在定义指针的同时完成初始化操作,即便该指针的指向尚未明确,也要将其初始化为空指针。
2. 在delete释放该指针后,对该指针赋值为空指针。
C++11 新增关键字 nullptr ,专门用来初始化空类型指针,nullptr并非整型类别,甚至也不是指针类型,但是能转换成任意指针类型。
而 NULL 在 C++ 中的定义 #define NULL 0 ,并且 C++ 中不能将void *类型的指针隐式转换成其他指针类型。
eg:
#include <iostream>
using namespace std;
void test_null(void* v) {
cout << "void*" << endl;
}
void test_null(int num) {
cout << num << endl;
}
int main() {
test_null(NULL); // 输出 0
test_null(27); // 输出 27
test_null((void*)NULL); // 输出 void*
test_null(nullptr); // 输出 void*
return 0;
}