首页 > 其他 > 详细

为什么应该使用nullptr

时间:2015-04-07 07:21:54      阅读:83      评论:0      收藏:0      [点我收藏+]


转载地址:http://www.stroustrup.com/bs_faq2.html#null

为什么应该使用nullptr呢,以下是c++之父的解释:

1down vote

Here is Bjarne Stroustrup‘s wordings,

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That‘s less common these days.

If you have to name the null pointer, call it nullptr; that‘s what it‘s called in C++11. Then, "nullptr" will be a keyword.

即:

在C++中,NULL就是0(#define NULL 0)(在C中,NULL被定义为0或void*),有时人们认为NULL和整数0是不同的,或者NULL不是个整数。

这就可能给程序带来二义性。比如以下重载函数:

void f(int)  ----------->f(0)

void f(const char *)----------->f(NULL) == f(0)

当使用f(NULL)时,你认为程序应该调用f(const char *),但现实情况中,f(NULL)调用的是f(int),这样就会出现二义性了。正确的调用方法应该是:f(nullptr);

而nullptr是一个指针类型( std::nullptr_t ),当你想命名一个空指针时,就用nullptr。

本文出自 “whatever957” 博客,请务必保留此出处http://whatever957.blog.51cto.com/6835003/1629343

为什么应该使用nullptr

原文:http://whatever957.blog.51cto.com/6835003/1629343

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