소멸자가 실제 작업을 수행하지 않는 것처럼 보이는 다음 코드를 고려하면 valgrind는 소멸자를 사용하지 않고 메모리 누수가 있음을 분명히 보여주었습니다. 어떤 경우라도 소멸자가하는 일은 무엇이든 설명 할 수 있습니까?소멸자는 자동으로 무엇을합니까?
#include <iostream>
using namespace std;
class A
{
private:
int value;
A* follower;
public:
A(int);
~A();
void insert(int);
};
A::A(int n)
{
value = n;
follower = NULL;
}
A::~A()
{
if (follower != NULL)
delete follower;
cout << "do nothing!" << endl;
}
void A::insert(int n)
{
if (this->follower == NULL) {
A* f = new A(n);
this->follower = f;
}
else
this->follower->insert(n);
}
int main(int argc, char* argv[])
{
A* objectA = new A(1);
int i;
for (i = 0; i < 10; i++)
objectA->insert(i);
delete objectA;
}
조용하지만 치명적인. 그것은 추종자를 삭제합니다. – Anycorn
네,하지만 실제로 삭제는 결국 아무 것도하지 않는 소멸자를 호출합니다. – zhanwu
당신의 소멸자가 포인터 "추종자"를 삭제한다고 생각합니다. memmory에 저장된 가치에 대한 언급을 잃었습니다. 그러나 memmory는 할당된다. 따라서 당신은 가치에 접근 할 수 없으며 당신은 당신의 기억 공간을 낭비합니다. – tomasBULL