测试代码:
#include <cstdlib>
#include <string>
#include <iostream>
#include <thread>
#include <array>
using namespace std;
void f(int test);
void f(void* test);
int main(int argc, char *argv[])
{
f(nullptr);
f(NULL);
f(0);
while(1);
return EXIT_SUCCESS;
}
void f(int test)
{
cout<<"int:test = "<<test<<endl;
}
void f(void* test)
{
cout<<"void*:test = "<<test<<endl;
}
输出结果:
int:test = 0
int:test = 0
分析:
在实际应用过程中如果 f 函数 参数是0 或者NULL或被编译器默认的认为是int,如果想调用void f(void* test) 要加强制转换 (void*)0或(void*)NULL可以解决这个问题。
这样就会引起可读性变差,或者忘记加强制性转换直接引入了bug。
为了解决上面的问题C++标准引入了nullptr 关键字,实际上他是一个 const 的 void* 指针,他对任何其他指针复制都会自动强制的转化为对应的指针类型。
本文通过一个简单的C++示例介绍了nullptr关键字的使用方法及其与0和NULL的区别。当函数参数为0或NULL时,编译器可能会将其当作整型处理,从而导致预期之外的行为。为了提高代码的可读性和避免潜在的错误,C++引入了nullptr来专门表示空指针,它能自动转换为目标指针类型。
1142

被折叠的 条评论
为什么被折叠?



