检查NULL值C++的引用

pra*_*ha6 1 c++ pointers reference pass-by-reference

我已经读过"检查引用是否等于null在C++中没有意义" - 因为引用永远不会有空值.但是,我看到这个陈述不适用于我想出的以下示例:

void InsertNode(struct node*& head, int data)
{
    cout << head << endl;

    node* temp = new node();
    temp->data = data;
    temp->next = NULL;

    if (head == NULL)
        head = temp;
    else
    {
        temp->next = head;
        head = temp;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在检查if (head == NULL).即使头部作为参考传递,我正在检查它是否等于NULL.这与我在"C++中检查引用是否等于null是无意义的"这句话相矛盾 - 如果我的理解是对的,请解释一下吗?谢谢.

Ulr*_*rdt 7

您不检查引用是否为null,但它是否引用空指针,这是不同的.

也许一个例子会有所帮助:

int i = 42;
// check if a variable is null
if (i == 0) print("i is null");

// pointer
int* pi = &i;
// check if a pointer is null
if (pi == 0) print("pi is null");
// check if a pointer points to a null
if (*pi == 0) print("i is null");

// reference
int& ri = i;
// check if a reference refers to a null
if (ri == 0) print("i is null");
Run Code Online (Sandbox Code Playgroud)

对引用的另一种描述可能有所帮助:引用是一种自解引用的非空指针.这意味着你永远不必写,*pi以获得它指向的对象,但只是ri.这也意味着它保证是非空的.请注意,您可以编写破坏此保证的程序,但这些程序无论如何都会导致所谓的未定义行为,因此不值得为此烦恼,因此最初使您困惑的语句.