析构函数默默地做什么?
考虑到下面的代码看起来析构函数没有做任何实际工作,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;
}
Considering the following code which looks like that the destructor doesn't do any real job, valgrind showed me clearly that it has memory leak without using the destructor. Any body can explain me what does the destructor do in this case?
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
insert() 方法在堆上创建新的 A 并使用跟随者指针将其链接到下一个元素。因此,如果 A 上没有析构函数,follower 指向的对象永远不会被删除。
The insert() method creates new A on the heap and links it to the next element with the follower pointer. So without the destructor on A, the object pointed to by follower never gets deleted.
首先,我们希望这是为了练习,否则
std::forward_list
似乎更合适(并且vector
可能会更好)。其次,析构函数的作用简单来说就是执行你放入其中的代码,这里的作用是释放
follower
获取的资源。对
delete follower
的调用做了两件事:follower
的析构函数follower
所在的内存> 被存储如果没有调用
delete
,就会出现内存泄漏。注意:
main
中,没有必要new
A
的实例。First, let us hope this is for exercise, otherwise a
std::forward_list<int>
seems much more adequate (and avector<int>
would probably be better).Second, the destructor role is, simply, to execute the code you put in it, which here is about releasing the resources acquired by
follower
.The call to
delete follower
does two things:follower
follower
was storedWithout the call to
delete
, you have a memory leak.Notes:
main
, tonew
the instance ofA
.这段代码看起来析构函数确实做了真正的工作:它删除了跟随者指针,该指针调用 ~A(),而 ~A() 又将删除其跟随者,依此类推。
如果省略析构函数,所有分配的节点将不会被删除。
This code looks like the destructor does do real job: it deletes follower pointer, which calls ~A(), which, in turn will delete its follower and so on.
If you omit the destructor all allocated nodes will not be deleted.