gpt4 book ai didi

c++ - 检查 NULL 值 C++ 的引用

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:17 25 4
gpt4 key购买 nike

我读到“检查引用是否等于 null 在 C++ 中是没有意义的”——因为引用永远不能有 null 值。但是,我发现这个声明在我提出的以下示例中并不成立:

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

我正在检查 if (head == NULL)。尽管 head 作为引用传递,但我正在检查它是否等于 NULL。这与我读到的声明“检查引用是否等于 null 在 C++ 中是没有意义的”相矛盾——如果我的理解是正确的,有人能解释一下吗?谢谢。

最佳答案

您不检查引用是否为空,而是检查它是否引用空指针,这是不同的。

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

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

关于引用的另一种描述可能会有所帮助:引用是一种自解除引用的非空指针。这意味着您永远不必编写 *pi 来获取它指向的对象,而只需编写 ri。这也意味着它保证是非空的。请注意,您可以编写违反此保证的程序,但这些程序无论如何都会导致所谓的未定义行为,因此不值得为此烦恼,因此不值得一开始让您感到困惑的声明。

关于c++ - 检查 NULL 值 C++ 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33094760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com