【发布时间】:2015-10-23 04:13:25
【问题描述】:
据我所知,c++ 为堆中的指针分配内存,当函数退出时,该指针不会自动释放。但是在下面的代码运行之后,我发现指针 a 是空的,即使它在类成员函数中分配了一些空间。
#include "string"
#include <iostream>
using namespace std;
class Test
{
public:
void test(int *a) {
if (a == 0)
{
a = new int[10];
bool a_is_null = (a == 0);
cout << "in class member function, after allocated, a is null or not?:" << a_is_null << endl;
}
};
};
int main() {
int *a = 0;
bool a_is_null = (a == 0);
cout << "in main function, before allocated, a is null or not?:" << a_is_null << endl;
Test t;
t.test(a);
a_is_null = (a == 0);
cout << "in main function, after allocated, a is null or not?:" << a_is_null << endl;
delete[] a;
cin;
}
This is the conducting result.
谁能告诉我为什么?
测试函数退出时是否会破坏new int[10]的内存?并且之后指针 a 仍然为空。
【问题讨论】:
-
“c++ 为堆中的指针分配内存”——不,你从哪里得到错误信息?
-
是的。你说的对。应该是operator 'new'分配的内存在堆中
标签: c++ pointers memory-management heap-memory