为什么类成员函数会破坏为指针参数分配的内存?

时间:2015-10-23 04:13:25

标签: c++ pointers memory-management heap

据我所知,c ++为堆中的指针分配内存,当函数退出时,它不会自动释放。但是在下面的代码运行之后,我发现指针a是null,即使它在类成员函数中被分配了一些空格。

#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在此之后仍为空。

1 个答案:

答案 0 :(得分:2)

指针与任何其他变量一样,并且您在行

中按值传递它
t.test(a);

因此,在函数退出后不会修改指针。通过引用传递它,你会看到差异,即声明

void Test::test(int* &a) { ...}

Live example