繁体   English   中英

在 c++ 中通过引用传递指针?

[英]pass a pointer by reference in c++?

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

这是我在上面的代码中的理解。

在主function中,首先定义了一个局部变量x
然后,定义一个名为ptr的指针变量,用x的 memory 地址初始化; 即, ptr是一个指针变量,它指向 int 变量x
之后,检查ptr是否为 null。 既然是用一个值初始化的,那它就不是空的吗?
之后,调用 function foo 在这里,function int *&ptr的参数可以理解为int* &ptr ,即这个 function foo 接受一个int* (一个指针参数),因为& int* &ptr是传引用的。 由于是按引用传递,因此指针ptr的内容会被更新。 所以在 function 调用之后,指针变量ptr现在有一个值nullptr 这就是为什么下一个std::cout会在屏幕上打印 null 的原因。

我希望我理解正确。 一个不相关的问题: null在 C++ 中什么都没有,对吧? 所以nullptr就像一个指向任何东西的指针?

您对代码的理解是正确的。 当你使用别名时,有时更容易理解指针的指针和指针的引用:

using int_ptr = int*;
void foo(int_ptr& ptr) // pass int_ptr by reference
{
    ptr = nullptr; // change the int_ptr that is referenced
}

这种别名通常不应该在实际代码中使用。

关于

“null”在 C++ 中什么都没有,对吧? 所以 nullptr 就像一个指向任何东西的指针?

是的,根据定义, nullptr不指向 object 或 function(因此不得取消引用)。 null作为关键字在 C++ 中不存在。 有关 C++ 中null指针的更多信息

是的,您对代码的理解是正确的。 只要有可能,就可以类比更简单的情况(比如你的情况下的整数)来理解事物。 指针是保存 memory 地址的变量。 null 指针概念意味着指针指向任何内容。 您可以在此处找到有关 null 概念的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM