1. 程式人生 > >NULL和nullptr的區別

NULL和nullptr的區別

NULL是0

nullptr是空指標void

  • 看例子:
#include <iostream>

void go(int num)
{
    std::cout << "go num" << std::endl;
}

void go(char *p)
{
    std::cout << "go p" << std::endl;
}

void main()
{
    void *p = NULL;

    go(p);//error C2665: “go”: 2 個過載中沒有一個可以轉換所有引數型別
}

在看例子就比較清晰了:

void go(int num)
{
    std::cout << "go num" << std::endl;
}

void go(void *p)
{
    std::cout << "go p" << std::endl;
}

int main()
{
    void *p = NULL;

    go(p);//go p

    go(NULL);//go num

    go(nullptr);//go p

    system("pause");

    return -1;
}

結果:

在這裡插入圖片描述

細節:

1)在c語言中NULL代表空指標。

例如:int *i = NULL;

#define NULL ((void*)0) 意思是NULL是void*指標,給int i 賦值的時候隱式轉換為相應型別的指標,但是如果換成c++編譯器編譯的時候會出錯,以為c++是強型別的,void 不能隱式轉換為其他型別。一般的NULL定義的標頭檔案為:

/* Define NULL pointer value /
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else /
__cplusplus */
#define NULL ((void )0)
#endif /

__cplusplus /
#endif /
NULL */

2)c++中 NULL代表0

c++ 中有函式過載的概念,會導致呼叫二義性。如

void bar(sometype1 a, sometype2 *b);
void bar(sometype1 a, int i);

bar(a,NULL)

  • 答案是 呼叫第二個!!!!!!
    呼叫程式碼也很快可能忽略過去了,因為我們用的是NULL空指標啊,應該是呼叫的void bar(sometype1 a, sometype2 *b)這個過載函式啊。實際上NULL在C++中就是0,寫NULL這個反而會讓你沒那麼警覺,因為NULL不夠“明顯”,而這裡如果是使用0來表示空指標,那就會夠“明顯”,因為0是空指標,它更是一個整形常量。

在C++中,使用0來做為空指標會比使用NULL來做空指標會讓你更加警覺。

3)c++11中的nullptr

用nullptr來表示空指標