让我详细说说,
如果我使用一个函数通过引用传递一个指针,然后该函数将一个新对象分配给它,有没有办法让该对象在程序退出该函数后保留在内存中。
这是我的意思的一个例子:(程序总是输出 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.
}