正常
nullptr (C++11)
In a Nutshell
A null pointer literal of type std::nullptr_t that safely distinguishes integer overloads, completely resolving the ambiguity caused by the macro NULL and the integer 0 in templates and function overloading.
Header
No header required (language keyword); the type is defined in <cstddef>.
Core API Quick Reference
| Operation | Signature | Description |
|---|---|---|
| Null pointer literal | nullptr | A prvalue of type std::nullptr_t |
| Implicit conversion | → Any pointer type | Converts to a null pointer value of the corresponding type |
| Implicit conversion | → Any member pointer type | Converts to a null member pointer value of the corresponding type |
Minimal Example
cpp
void f(int* p) {
// Handle pointer
}
void f(int i) {
// Handle integer
}
int main() {
// Calls f(int*)
f(nullptr);
// Calls f(int)
f(0);
}Embedded Applicability: High
- A zero-overhead abstraction; the compiler directly generates a null pointer value, producing the same instructions as
0orNULL. - Avoids ambiguity between integer and pointer overloads in register manipulation functions (e.g., overloads for hardware registers).
- Behaves correctly in template metaprogramming (e.g., static assertions, type traits), whereas
NULLand0would fail. - Fully compatible with C-style low-level hardware manipulation code, allowing for risk-free, gradual replacement.
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 4.6 | 3.0 | 2010 |
See Also
部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可