類型差異
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
;