导致内存泄漏的原因是什么?什么是内存泄漏的确切定义?
还有一个问题,为什么调用getC会导致内存问题?
class C
{
public:
C(int k) : arrSize(k)
{
arr = new int[k];
}
~C()
{
delete arr;
}
private:
int arrSize;
int *arr;
};
class B
{
public:
C& getC()
{
C c(8);
return c;
}
};
答案 0 :(得分:2)
class C
{
public:
C(int k) : arrSize(k)
{
arr = new int[k];
}
C(const C&); // you need to add this (Lookup: Rule of 3)
C& operator=(const C&); // you need to add this (Lookup: Rule of 3)
~C() // this is 1 of the Rule of 3, so you need all 3
{
delete arr; // this needed to be: delete [] arr;
} // since you did a new [] in the constructor
private:
int arrSize;
int *arr;
};
class B
{
public:
C& getC()
{
C c(8); // * see Note
return c;
}
};
c
的内容将被覆盖(损坏)内存泄漏与内存增长之间存在差异 - 不使用delete []
会导致泄漏。泄漏是指没有对已分配内存的引用。内存增长通常称为泄漏,但是在内存具有引用但不会被使用时发生,例如,保留已释放内存列表的分配器,但永远不会使其可用于重用。由于列表存在,它不是泄漏,而是内存增长。