如何将指针分配给功能中的新对象,而不会使该对象在退出后消失



让我详细说明一下,

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

下面是我的意思的示例:(程序始终输出 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.
}

如果你想看到对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.
}

您需要额外的间接寻址,如参考:

void assign_int(int *&a) {
    a = new int;
    *a = 5;
}

最新更新