C++中的NULL与nullptr

在C语言中使用NULL作为指针的初始化值,但C++中却建议使用nullptr

NULL其实是宏定义,即

#ifndef NULL
    #ifdef __cplusplus
        #define NULL 0
    #else
        #define NULL ((void *)0)
    #endif
#endif

nullptr 的类型为 std::nullptr_t(既不是整数类型,也不是指针类型),它可以隐式转换为任何指针类型。

使用NULL可能导致重载函数解析中的歧义,因为它既是整数,也是一个指针。以下述例子为例:

#include <iostream>
using namespace std;

void f(int num)
{
    cout << "整数" << endl;
    cout << num << endl;
}

void f(void *num)
{
    cout << "指针" << endl;
    cout << num << endl;
}

int main()
{
    f(NULL);
    return 0;
}

允许编译命令g++ test.cpp -o test会报如下错误:

test.cpp: In function ‘int main()’:
test.cpp:18:6: error: call of overloaded ‘f(NULL)’ is ambiguous
   18 |     f(NULL);

测试环境为Ubuntu

c++11
37 views
Comments
登录后评论
Sign In