[EMC++] Item 8. Prefer nullptr to 0 and NULL
生活随笔
收集整理的這篇文章主要介紹了
[EMC++] Item 8. Prefer nullptr to 0 and NULL
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
條款八 傾向使用nullptr而非0和NULL
簡介
在C++中的字面量0是一個int,當C++在一個只可以使用指針的情景中找到0,它勉強地把其解釋為null指針。
對于NULL也有類似的問題,具體實現允許給NULL一個整型(不一定是int,也可以是long等)。
但是最大的問題是0與NULL都不是指針類型
在C++98中,主要的問題是在指針和整形的重載中會導致困惑
// 傳遞0或者NULL永遠不會調用指針的重載函數 void f(int); void f(bool); void f(void*);f(0); // call f(int) f(NULL); // may not compile, typically calls f(int)調用的主要問題在于,代碼的表面意思(函數)與實際意思(整形)相互矛盾。
nullptr既不是一個整型,也不是一個指針類型,你可以把它看做一個指向所有類型的指針,其真正的類型是std::nullptr_t,它能隱性轉換為所有的指針類型。
案例
以下是調用鎖的一段程序,且能正確運行,但是有些瑕疵:
int f1(std::shared_ptr<Widget> spw); double f2(std::unique_ptr<Widget> upw); bool f3(Widget* pw);std::mutex f1m, f2m, f3m; using MuxGuard = std::lock_guard<std::mutex>; {MuxGuard g(f1m);auto result = f1(0); } {MuxGuard g(f2m);auto result = f2(NULL); } {MuxGuard g(f3m);auto result = f3(nullptr); }可以改寫為模板調用方式:
template<typename FuncType, typename MuxType, typename PtrType> decltype(auto) lockAndCall(FuncType func, MuxType& mutex, PtrType ptr) {MuxGuard g(mutex);return func(ptr); } auto result1 = lockAndCall(f1, f1m, 0); // error! auto result2 = lockAndCall(f2, f2m, NULL); // error! auto result3 = lockAndCall(f3, f3m, nullptr); // fine在第一個調用中,由于0被推斷為int類型,而把int當作std::unique_ptr<Widget>類型傳遞時發生錯誤。第二個調用類似。
總結
傾向使用nullptr而非0和NULL
避免整形與指針
總結
以上是生活随笔為你收集整理的[EMC++] Item 8. Prefer nullptr to 0 and NULL的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的脚印
- 下一篇: Linux系统分区和挂载浅谈