类型差异
NULL
和0
#include <iostream> template <typename T> void show( T&& a) { a.error(); } int main () { show(NULL); }
输出
D:\codes\cfile\Test\test.cpp: In instantiation of 'void show(T&&) [with T = long long int]': D:\codes\cfile\Test\test.cpp:8:14: required from here D:\codes\cfile\Test\test.cpp:4:7: error: request for member 'error' in 'a', which is of non-class type 'long long int' a.error(); ~~^~~~~ [Finished in 328ms]
这里
NULL
是long long int
类型.不同编译器实现不同.
问题
NULL
和0
都是内置类型,当出现同时重载指针和内置类型时. 会出现错误匹配或者二义性.错误匹配
#include <iostream> void show(long long int) { std::cout << __LINE__ << std::endl; } void show(void *) { std::cout << __LINE__ << std::endl; } int main () { show(NULL); }
二义性
#include <iostream> void show(bool) { std::cout << __LINE__ << std::endl; } void show(void *) { std::cout << __LINE__ << std::endl; } int main () { show(NULL); }
小结
nullptr
是关键字.不需要include
nullptr
有自己的类型,不会和普通类型出现二义性.
nullptr
可以转化为任意类型的指针.
nullptr
有编译器支持,C++11
新特性.
好处
可读性
#include <iostream> void* show() { return nullptr; } int main () { auto s = show(); if (0 != s) { } if (NULL != s) { } if (nullptr != s) { } }
nullptr
是后面的主流.
NULL
和nullptr
一起有点混.
0
都不知道返回的是什么类型.
模板
分析
前面介绍了
NULL,0
当作空指针,间接隐式转换还可以,但是通过模板就会变回原形.变回原型就不匹配,会出现警告之类的.
隐式匹配
#include <iostream> void show(void*) { } int main () { show(0); show(NULL); }
关键是还不能出现自身类型的重载,出现了就可能出错.
模板现原形
#include <iostream> void cool(void*) { } template <typename T> void show(T&&a) { cool(a); } int main () { show(nullptr); // show(0); // show(NULL); }
直接报错.
总结
内置类型方便,安全.
兼容性强.不推荐使用
NULL,0
;