在C ++ 11中,最好使用零或NULL? [英] Whats better to use in C++11 , Zero or NULL?

查看:97
本文介绍了在C ++ 11中,最好使用零或NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,对于C ++ 11,ZeroNULL建议使用什么?如果是第二个中的第一个?

Nowadays, with C++11, Whats recommended to use, Zero or NULL? The first of the second if?

int * p = getPointer();

if( 0 == p ){
    // something
}

if( NULL == p ){
    // something
}

更新:我忘记了新的

if( nullptr == p ){
    // something
}

更新2:这些示例旨在显示写空指针的选项,我知道写if( !p )会更令人愉快.

UPDATE 2: the examples are to show the options to write null pointer, I know is more pleasant to write if( !p ).

推荐答案

其他答案正确.但是我想再说一下为什么 nullptr更好.

The other answers are right. But I wanted to say a little more about why nullptr is better.

在C ++ 11中,完美转发"非常重要.它无处不在.明显的地方是bindfunction.但是它也可以在其掩护下的许多其他地方使用.但是完美转发"并不完美.它失败的地方之一是空指针常量.

In C++11 "perfect forwarding" is very important. It is used everywhere. Obvious places are bind and function. But it is also used in a multitude of other places under the covers. But "perfect forwarding" isn't perfect. And one of the places it fails is null pointer constants.

template <class T>
void display(T)
{
    std::cout << type_name<T>() << '\n';
}

template <class T>
void
f(T&& t)
{
    display(std::forward<T>(t));  // "perfectly forward" T
}

int main()
{
    f(0);
    f(NULL);
    f(nullptr);
}

type_name<T>()的适当定义下,在我的系统上打印出来:

With an appropriate definition of type_name<T>(), on my system this prints out:

int
long
std::nullptr_t

这可以轻松地在工作代码和错误之间进行区分.运气好的话,您的错误就会在编译时出现(带有错误的错误消息).但是在某些情况下,您也可能会遇到运行时错误.

This can easily make the difference between working code and errors. With any luck your errors will come at compile time (with horrible error messages). But you may also get run time errors in some circumstances.

积极禁止在代码中使用0和NULL.

即使您在代码中的转发不完善,调用的代码(例如std :: lib)也很可能在幕后使用它.

Even if you're not perfect forwarding in your code, code you call (such as the std::lib) is very likely using it under the covers.

这篇关于在C ++ 11中,最好使用零或NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆