Namespaces
Variants

nullptr , the pointer literal (since C++11)

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

目录

语法

nullptr

说明

关键字 nullptr 表示指针字面量。它是 std::nullptr_t 类型的 纯右值 。存在从 nullptr 到任何指针类型和任何成员指针类型的空指针值的 隐式转换 。类似的转换也存在于任何空指针常量,包括 std::nullptr_t 类型的值以及宏 NULL

关键词

nullptr

示例

演示即使 nullptr 不再是字面量,它仍保留空指针常量的含义。

#include <cstddef>
#include <iostream>
template<class T>
constexpr T clone(const T& t)
{
    return t;
}
void g(int*)
{
    std::cout << "Function g called\n";
}
int main()
{
    g(nullptr);        // 正常
    g(NULL);           // 正常
    g(0);              // 正常
    g(clone(nullptr)); // 正常
//  g(clone(NULL));    // 错误:非字面量零不能作为空指针常量
//  g(clone(0));       // 错误:非字面量零不能作为空指针常量
}

输出:

Function g called
Function g called
Function g called
Function g called

参考文献

  • C++23 标准 (ISO/IEC 14882:2024):
  • 7.3.12 指针转换 [conv.ptr]
  • C++20 标准 (ISO/IEC 14882:2020):
  • 7.3.12 指针转换 [conv.ptr]
  • C++17 标准 (ISO/IEC 14882:2017):
  • 7.11 指针转换 [conv.ptr]
  • C++14 标准 (ISO/IEC 14882:2014):
  • 4.10 指针转换 [conv.ptr]
  • C++11 标准 (ISO/IEC 14882:2011):
  • 4.10 指针转换 [conv.ptr]

参见

实现定义的空指针常量
(宏常量)
(C++11)
空指针字面量 nullptr 的类型
(类型别名)
C 文档 关于 nullptr