nullptr (C++11) คือ pointer literal แทน null pointer แทนที่ NULL (มัก define เป็น 0 หรือ (void*)0)
ปัญหาของ NULL
void func(int); void func(char*); func(NULL); // Ambiguous! NULL อาจเป็น int 0 หรือ pointer
แก้ด้วย nullptr
func(nullptr); // ชัดเจน: เรียก func(char*)
คุณสมบัติ
-
ชนิด
- แปลงเป็น pointer type ใดๆ ได้โดยอัตโนมัติ (implicit conversion)
- ไม่ แปลงเป็น integral type (int, long) ได้ → ป้องกัน ambiguity
- ใช้แทน NULL ได้ทุกที่ที่คาดหวัง pointer
std::nullptr_t
ตัวอย่าง
int* p1 = nullptr; // OK int* p2 = NULL; // OK (แต่เก่า) int x = nullptr; // Error: cannot convert to int int x = NULL; // OK (แต่อาจผิดพลาดทางตรรกะ) bool b = nullptr; // OK: false (contextual conversion to bool)
ใช้ nullptr เสมอใน C++11+ เพื่อความปลอดภัยและชัดเจน