首页 > 解决方案 > 如何将指针分配给函数中的新对象,而该对象在退出后不会消失

问题描述

让我详细说明,

如果我使用函数通过引用传递指针,然后该函数为其分配一个新对象,那么在程序退出函数后,该对象是否可以保留在内存中。

这是我的意思的一个例子:(程序总是输出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;}
}

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

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

标签: c++functionpointersscopelinked-list

解决方案


在你的函数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.
}

如果您希望看到对 in 所做的更改i反映foo在 中main,则必须通过引用接受该变量。

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

指针也不例外。

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

推荐阅读