为什么 class 成员函数会破坏为指针参数分配的内存?
Why class member function destroies the memory allocated for a pointer argument?
据我所知,c++ 为堆中的指针分配内存,当函数退出时不会自动释放。但是在运行下面的代码之后,我发现指针a是空的,即使它在class成员函数中分配了一些space。
#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 仍然为 null。
指针与任何其他变量一样,您在
行中按值传递它
t.test(a);
因此函数退出后指针没有被修改。通过引用传递它,你会看到不同之处,即 declare
void Test::test(int* &a) { ...}
据我所知,c++ 为堆中的指针分配内存,当函数退出时不会自动释放。但是在运行下面的代码之后,我发现指针a是空的,即使它在class成员函数中分配了一些space。
#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 仍然为 null。
指针与任何其他变量一样,您在
行中按值传递它t.test(a);
因此函数退出后指针没有被修改。通过引用传递它,你会看到不同之处,即 declare
void Test::test(int* &a) { ...}