Whats better to use in C++11 , Zero or NULL?

前端 未结 4 1223
陌清茗
陌清茗 2021-02-04 05:19

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

int * p = getPointer();

if( 0 == p ){
    //         


        
相关标签:
4条回答
  • 2021-02-04 05:28

    C++11 has a new literal keyword nullptr. It's better than 0 or NULL for things like this because there's no chance it will be used as an int in overload resolution.

    if ( nullptr == p )
    

    Or of course you can just use a pointer in a bool context:

    if ( !p )
    
    0 讨论(0)
  • 2021-02-04 05:29

    If you have the same problem in 2019, You are using an older initialization style for unassigned pointers. After 2014 August 14 the C++ 11 released. The compiler you are using is probably following the C++11 standard.

    You can just replace 0/NULL with nullptr

    Modern C++ offers nullptr as a universal null pointer. You should use that instead of 0 || NULL because there are some obscure machines that have things like signed pointers where a null pointer is actually something like -1 rather than 0.

    0 讨论(0)
  • 2021-02-04 05:35

    Neither, it's nullptr.

    Though, in your case, I'd just go with

    if ( !p ){
       //something
    }
    

    2.14.7 Pointer literals [lex.nullptr]

    1 The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t. [ Note: std::nullptr_t is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value.

    0 讨论(0)
  • 2021-02-04 05:43

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

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

    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.

    Aggressively ban use of 0 and NULL in your code.

    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.

    0 讨论(0)
提交回复
热议问题