如何从抽象类中删除指针

How do i delete a pointer from an abstract class

本文关键字:删除 指针 抽象类      更新时间:2023-10-16

我是C++和CS的新手。我无法理解如何完全防止内存泄漏。我有一个名为 shape 的抽象类,我使用抽象类设置了一个指针。但是,当我尝试删除指针时,我仍然发现内存泄漏。与valgrind检查时,我收到此消息

==14227== HEAP SUMMARY:
==14227==     in use at exit: 72,704 bytes in 1 blocks
==14227==   total heap usage: 3 allocs, 2 frees, 73,760 bytes allocated
==14227== 
==14227== LEAK SUMMARY:
==14227==    definitely lost: 0 bytes in 0 blocks
==14227==    indirectly lost: 0 bytes in 0 blocks
==14227==      possibly lost: 0 bytes in 0 blocks
==14227==    still reachable: 72,704 bytes in 1 blocks
==14227==         suppressed: 0 bytes in 0 blocks
==14227== Rerun with --leak-check=full to see details of leaked memory 
==14227== 

形状.hpp

class Shape
{
 protected:
     int sides;
     int length;
     int width
 public:
     virtual int perimeter() = 0;
     virtual int area() = 0;
     virtual ~Shape(){}
};

矩形.hpp

class Rectangle : public Shape
{
 public:
     Rectangle();
     virtual int perimeter();
     virtual int area();
     void setLength(int);
     void setWidth(int);
     int getLength();
};

矩形.cpp

Rectangle::Rectangle()
{
 setLength(2);
 setWidth(5);
}
void Rectangle::setLength(int l)
{length = l;}
void Rectangle::setWidth(int w)
{width = w}
int Rectangle::perimeter()
{enter code here}
int Rectangle::area()
{enter code here}
int Rectangle::getLength()
{return length;}

主.cpp

Shape *s1;
int main()
{
 s1 = new Rectangle();
 cout << "Length: " << s1->getLength() << endl;
 delete s1;
 return 0;
 }

很好,您编辑了您的问题,以便矩形构造函数是公开的。否则,它不可能编译。

您可以正确地将形状析构函数定义为虚拟。因此,您将删除形状指针。

我不习惯Valgrind,(我C++Windows开发(你确定瓦尔格林德在谈论指向你的形状对象的指针吗?

你能列出仍然在瓦尔格林德分配的指针值吗?也许检查其内存内容可以向您保证不是您的对象导致了此分配。

编辑:你可以做的一个技巧,如果你不知道如何使用gdb逐步调试,你可以这样做:

virtual ~Rectangle()
{
   std::cout << " proof the destructor has been called";
}

如果你确实在输出中看到跟踪,那么你将质疑Valgrind诊断,而不是你的代码。

泄漏摘要似乎有些混乱。

Valgrind表示它没有发现内存泄漏:

==14227== LEAK SUMMARY:
==14227==    definitely lost: 0 bytes in 0 blocks
==14227==    indirectly lost: 0 bytes in 0 blocks
==14227==      possibly lost: 0 bytes in 0 blocks

以下行==14227== still reachable: 72,704 bytes in 1 blocks突出显示程序退出时的堆使用情况。