c++ - 如何将指针分配给函数中的新对象,而该对象在退出后不会消失
问题描述
让我详细说明,
如果我使用函数通过引用传递指针,然后该函数为其分配一个新对象,那么在程序退出函数后,该对象是否可以保留在内存中。
这是我的意思的一个例子:(程序总是输出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.
}
如果您希望看到对 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.
}
推荐阅读
- java - RC2 加密结果在 Python 和 Java 中的差异
- c++ - C++ 派生类无法访问受保护的成员,除非使用默认构造函数
- linux - 在 docker run 中执行 ls /mnt 时没有这样的文件
- javascript - Javascript 分组和排序
- julia - 如何在@formula 宏中使用字符变量?
- php - 使用 html 和 php 传递两个值(一个来自文本,一个隐藏)
- c# - 如何在Castle.Core中实现IProxyGenerationHook的类中实现Equals和GetHashCode的覆盖方法?
- swift - Swift 将 Decodable 结构转换为 Dictionary
- mysql - Django 无法连接到 MySQL 容器?
- vb.net - 使用许多过滤器计算数据表