码迷,mamicode.com
首页 > 其他好文 > 详细

为什么应该使用nullptr

时间:2015-04-07 07:23:20      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:nullptr null 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

标签:nullptr null 0

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!