如何从抽象类中删除指针
How do i delete a pointer from an abstract class
我是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
突出显示程序退出时的堆使用情况。
相关文章:
- 无法删除指针,已触发断点
- 删除指针数组 (C++) 中的元素
- 如果我删除指针,我的C++程序会意外删除系统文件吗?
- 为什么const_cast删除指针的恒常性,而不删除指向常量的指针的恒常性?
- 删除指针后内存泄漏
- 这是系统资源吗?(或者我怎么知道我是否需要删除指针) - 在 C++ 中使用 C
- C++ 从 2 组指针中删除指针
- 当删除 [] 指针工作时,为什么无法获得指向的数组大小?
- 在这种情况下,删除指针数组期间会发生什么?
- 在C++中删除指针数组时析构函数崩溃
- 何时/如何在使用指针后正确删除指针?
- 在C++库中,谁应该删除指针、用户或库?
- 删除指针后阻止对象使用 "this"
- 删除指针后C++尝试/捕获
- 删除指针内存分配以避免内存泄漏
- 删除指针时,未分配被释放的 C++ 指针错误
- 如何从抽象类中删除指针
- 我应该在 v8::外部手动删除指针吗?
- 删除指针
- C 如何删除指针的默认对象成员