C++ 中 NULL 通常定義為 0(整型),而非 (void*)0。導致重載決議、模板推導出錯:
void f(int); void f(void*); f(NULL); // 調用 f(int),而非 f(void*)!
綁定函數指針時也會報錯:
void cb(void* data); bind(cb, obj, NULL); // 錯誤:NULL 推導為 int,非 void*
std::nullptr_t,可隱式轉換為任意指針類型、成員指針類型。NULL 完全兼容的語義,但類型安全。const class nullptr_t {
public:
template<class T> operator T*() const { return 0; }
template<class C, class T> operator T C::*() const { return 0; }
private:
void operator&() const; // 禁止取地址
} nullptr_t = {};
#undef NULL
#define NULL nullptr_t
NULL(宏)與 nullptr(關鍵字),無 null。null 為關鍵字/字面量。NULL 表示缺失值,IS NULL 判斷,ISNULL() 替換。null 為原始值,undefined 為未定義。nullptr,禁用 NULL。nullptr 或逐步替換。nullptr 避免推導為整型。