#include <iostream>
void foo(int *&ptr) // pass pointer by reference
{
ptr = nullptr; // this changes the actual ptr argument passed in,not a copy
}
int main()
{
int x = 5;
int *ptr = &x; // create a pointer variable ptr,which is initialize with the memory address of x; that is,ptr is a pointer which is pointing to int variable x
std::cout << "ptr is: " << (ptr ? "non-null" : "null") << '\n'; // prints non-null
foo(ptr);
std::cout << "ptr is: " << (ptr ? "non-null" : "null") << '\n'; // prints null
return 0;
}
这是我在上面的代码中的理解方式。
在main函数中,首先定义局部变量x
。
然后,定义一个名称为ptr
的指针变量,该变量用x
的内存地址初始化;即ptr
是一个指向int变量x
的指针变量。
之后,检查ptr
是否为空。由于它是使用值初始化的,因此不是null吗?
之后,将调用函数foo
。在这里,函数int *&ptr
的参数可以理解为
int* &ptr
,即此函数foo接受int*
(指针参数),并且由于&
中的int* &ptr
而成为引用传递。由于它是按引用传递的,因此指针ptr
的内容被更新。因此,在函数调用之后,指针变量ptr
现在具有值nullptr
。这就是为什么下一个std::cout
将在屏幕上显示null的原因。
我希望我能正确理解。一个不相关的问题:null
在C ++中是什么,对吗?所以nullptr
就像一个指向什么都没有的指针?