c++ - 如何在函数中分配指向新对象的指针,而该对象在编辑后不会消失

标签 c++ function pointers scope linked-list

<分区>

让我详细说说,

如果我使用一个函数通过引用传递一个指针,然后该函数将一个新对象分配给它,有没有办法让该对象在程序退出该函数后保留在内存中。

这是我的意思的一个例子:(程序总是输出 NULL)

#include <iostream>
using namespace std;

void assign_int(int *a) { //<-- assigns some number to the pointer
    a = new int;
    *a = 5;
}

int main() {

    int *a = NULL;
    assign_int(a);

    if(a == NULL) {cout << "NULL";} //<-- checks whether or not the number is there.
    else {cout << *a;}
}

我一直致力于使用指针和节点(每个节点由一个数字和一个指针组成)来实现链表,但是一旦我离开创建列表的函数,所有新节点都会被删除,并且列表变为空。

我知道局部变量一旦离开声明的范围就会被删除,但有没有办法避免这种情况?

最佳答案

在你的函数 assign_int 中,a 是一个函数局部变量。对其的任何更改都不会影响调用函数中变量的值。

使用更简单类型的对象可以更清楚地理解这个问题。

void foo(int i)
{
   i = 10; // This changes the local variable's value.
}

int main()
{
   int i = 20;
   foo(i);

   // Value of i is still 20 in this function.
}

如果你想看到在 foo 中对 i 所做的更改反射(reflect)在 main 中,你必须接受变量通过引用。

void foo(int& i)
{
   i = 10; // This changes the value of the variable in the calling function too.
}

指针也不异常(exception)。

void assign_int(int *a) {
    a = new int;  // This changes the local variable's value.
    *a = 5;       // This changes the value of object the local variable points to
}

要查看 a 的新值及其指向的对象,assign_int 必须通过引用接受指针。

void assign_int(int*& a) {
    a = new int;  // This changes the value of the variable in the calling function too.
    *a = 5;       // The value of the object the pointer points to will be visible in 
                  // the calling function.
}

关于c++ - 如何在函数中分配指向新对象的指针,而该对象在编辑后不会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484947/

相关文章:

c++ - 双 const 声明

Javascript 函数行为

c++ - C++ 编译器是否会独立决定内联 lambda 函数及其调用者?

c++ - 将成员函数作为参数传递

c - 在c中编辑字符串数组

c# - 将 C++ 函数重写为 C#(将指针传递给数组中的下一个元素)

c++ - 我的文档的空白自由路径

c++ - 如何避免在我的代码中频繁键入 namespace::overly?

C++ 不能在结构中存储指针

c - 矩阵作为C中的双指针,如何移动它