nullptr,NULL和0

推荐使用nullptr,因为
NULL和0本质上是整形,nullptr的真正类型是std::nullptr_t,std::nullptr_t能够被隐式转换为任何类型的裸指针,因此可以看成是指向所有类型的指针。
传递0或者NULL给重载了整型参数和指针参数的函数会导致意料之外的情况,如下

void f(int); // three overloads of f
void f(bool);
void f(void*);
f(0); // calls f(int), not f(void*)
f(NULL); // might not compile, but typically calls
 // f(int). Never calls f(void*)

除此之外,使用nullptr更好的最主要原因是,当你想让0或NULL表示空指针时,对0或NULL做模板类型推导会推出“错误”的类型(推出他们本身的类型——整形,而不是想让他们表示的空指针类型)。比如:

int f1(std::shared_ptr<Widget> spw); // call these only when
double f2(std::unique_ptr<Widget> upw); // the appropriate
bool f3(Widget* pw); 

std::mutex f1m, f2m, f3m; 

template<typename FuncType,
 typename MuxType,
 typename PtrType>
auto lockAndCall(FuncType func,
 MuxType& mutex,
 PtrType ptr) -> decltype(func(ptr))
{
 MuxGuard g(mutex);
 return func(ptr);
}

auto result1 = lockAndCall(f1, f1m, 0); // error!

auto result2 = lockAndCall(f2, f2m, NULL); // error!

auto result3 = lockAndCall(f3, f3m, nullptr); // fine

第一个call传入0作为参数ptr,推导为int类型,传递给函数f1,而f1的形参类型为std::shared_ptr< Widget >,不匹配。第二个call同理。
而第三个call使用nullptr就没有这种错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值