🐭 C++ 中的空指针
在 C++ 的特定上下文中 0, NULL 都可以用来表示空指针,而且对于 NULL 的定义是由各家编译器的具体实现来决定的,这个一直比较混乱。C++11 中的 nullptr_t 类型为空指针引入了单独的明确的强类型定义,结束了空指针的混乱局面。我们应该尽可能的在一切需要空指针的地方无脑的使用 nullptr 来避免空指针类型混乱问题。
#include <iostream>int main(void) {// $ clang++ -v// Apple clang version 11.0.3 (clang-1103.0.32.59)// Target: x86_64-apple-darwin19.4.0// Thread model: posix// InstalledDir: /Library/Developer/CommandLineTools/usr/binusing std::cout, std::is_same_v;cout.setf(std::ios_base::boolalpha);auto n = NULL;// NULL is defined as 0L in my clang++ (c++ mode)// NULL is defined as ((void*)0) in my clang (c mode)cout << is_same_v<decltype(n), long> << '\n'; // truelong x = 0; // 0 is intlong *px = 0; // 0 is null pointerlong y = NULL; // NULL is longlong *py = NULL; // NULL is null pointer// long z = nullptr; // not compileslong *pz = nullptr; // nullptr is null pointercout << is_same_v<decltype(nullptr), std::nullptr_t> << '\n'; // truecout << is_same_v<decltype(pz), long *> << '\n'; // truereturn 0;}
:::tips std::nullptr_t 是由 nullptr 循环定义而来,nullptr 可以表示任何类型的空指针类型 :::
🐂 空指针与函数重载
由于 0, NULL 在特定上下文中具有二义性,对于函数重载来说,二义性会导致重载决议问题。另外,当函数模板涉及到指针类型推导时只有 nullptr 会推导为空指针。
对于一般函数重载来说,就是匹配最佳参数:
代码示例 :
#include <iostream>void f(int) { std::cout << "calls f(int)\n"; };void f(long) { std::cout << "calls f(long)\n"; };void f(bool) { std::cout << "calls f(bool)\n"; };void f(void *) { std::cout << "calls f(void *)\n"; };int main(void) {// $ clang++ -v// Apple clang version 11.0.3 (clang-1103.0.32.59)// Target: x86_64-apple-darwin19.4.0// Thread model: posix// InstalledDir: /Library/Developer/CommandLineTools/usr/binf(0); // calls f(int)f((void *)0); // calls f(void *)f((bool)0); // calls f(bool)f(NULL); // calls f(long)f(nullptr); // calls f(void *)return 0;}
:::tips
‘0’ 的最佳匹配当然是 ‘int’
‘NULL’ 的最佳匹配当然是 ‘long’
‘nullptr’ 的最佳匹配当然是 ‘void *’,当然也可以匹配其他任何指针类型
:::
对于模板重载来说,涉及到类型推导:
代码示例 :
#include <iostream>// shared pointerint f1(std::shared_ptr<int> sp) { return 1; };// unique pointerdouble f2(std::unique_ptr<int> up) { return 1.0; };// raw pointerbool f3(int *rp) { return true; };template <typename FuncType, typename PtrType>decltype(auto) call(FuncType func, PtrType ptr) {return func(ptr);}int main(void) {// both works without templatef1(0), f2(0), f3(0);f1(NULL), f2(NULL), f3(NULL);f1(nullptr), f2(nullptr), f3(nullptr);// since 0 is int, and NULL is long, below two lines of code not compiles// call(f1, 0), call(f2, 0), call(f3, 0);// call(f1, NULL), call(f2, NULL), call(f3, NULL);call(f1, nullptr), call(f2, nullptr), call(f3, nullptr);return 0;}
:::tips 函数模板指针类型推导,’0’ 被推导为 ‘int’,’NULL’ 被推导为 ‘long’,只有 ‘nullptr’ 会被推导为广义空指针 :::
🐯 总结
- 总是使用 nullptr 来替代 0, NULL 表示空指针
- 尽量不要设计形参为整型与指针的重载函数,避免误用
