【问题标题】:Why class member function destroies the memory allocated for a pointer argument?为什么类成员函数会破坏为指针参数分配的内存?
【发布时间】: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


【解决方案1】:

指针与任何其他变量一样,您在行中按值传递它

t.test(a);

因此函数退出后指针不会被修改。通过引用传递它,您会看到不同之处,即声明

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

Live example

【讨论】:

  • 是的。根据您的建议,事情发生了变化。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 2013-08-16
  • 2013-10-12
相关资源
最近更新 更多