如何将指针分配给函数中的新对象,而该对象在退出后不会消失[重复]

Posted

技术标签:

【中文标题】如何将指针分配给函数中的新对象,而该对象在退出后不会消失[重复]【英文标题】:How do I assign a pointer to a new object within a funcion, without that object dissapearing after exiting it [duplicate] 【发布时间】:2019-10-22 09:47:18 【问题描述】:

让我详细说明,

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

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

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

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

【问题讨论】:

您希望void assign_int(int *&amp;a) 看到函数外所做的更改。 您的using namespace std; 将您的代码延长了 9 个字节。 Stop using it. 【参考方案1】:

在您的函数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 所做的更改反映在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.

【讨论】:

哦,所以我使用的函数实际上创建了一个重复的指针,而重复的就是分配给数字的那个。我现在看到问题了,谢谢:] @leo,不客气。很高兴我能提供帮助。【参考方案2】:

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

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

【讨论】:

但是你不太可能这样做,而不是通过函数的返回值返回指针。 哦,解决了。我现在觉得自己很笨。-.

以上是关于如何将指针分配给函数中的新对象,而该对象在退出后不会消失[重复]的主要内容,如果未能解决你的问题,请参考以下文章

将派生对象分配给函数内的基类指针

将指向单例的指针分配给对象字段

将指针分配给字符串对象的第一个和最后一个索引

将第二个指针分配给第一个指针指向的对象

为啥即使我们将指针分配给NULL,指针的指向对象的大小也不为零?

使用循环将属性分配给对象