为什么类成员函数会销毁为指针参数分配的内存

Why class member function destroies the memory allocated for a pointer argument?

本文关键字:参数 指针 分配 内存 成员 函数 为什么      更新时间:2023-10-16

据我所知,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;
}

这是导电的结果。

谁能告诉我为什么?

test函数退出时是否会破坏new int[10]的内存?所以指针a在那之后仍然是空的

指针和其他变量一样,在

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

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

void Test::test(int* &a) { ...}
<<p> 生活例子/kbd>