首页 > 编程语言 > 详细

c++11 std - nullptr

时间:2014-02-17 15:30:14      阅读:388      评论:0      收藏:0      [点我收藏+]

测试代码:

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

输出结果:

bubuko.com,布布扣
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* 指针,他对任何其他指针复制都会自动强制的转化为对应的指针类型。

c++11 std - nullptr

原文:http://blog.csdn.net/drivermonkey/article/details/19300327

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!