c++11 std - nullptr

来源:互联网 发布:排序算法有几种 编辑:程序博客网 时间:2024/05/16 14:16

测试代码:

#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;   }

输出结果:

void*:test = 0
int:test = 0
int:test = 0

分析:

在实际应用过程中如果 f 函数 参数是0 或者NULL或被编译器默认的认为是int,如果想调用void f(void* test) 要加强制转换 (void*)0或(void*)NULL可以解决这个问题。

这样就会引起可读性变差,或者忘记加强制性转换直接引入了bug。

为了解决上面的问题C++标准引入了nullptr 关键字,实际上他是一个 const 的 void* 指针,他对任何其他指针复制都会自动强制的转化为对应的指针类型。

0 0
原创粉丝点击