我试图尽可能释放内存,但在调用delete时我会一直触发断点。自从我完成c ++以来已经有一段时间了,所以我不记得确切的方法。
的main.cpp
int _tmain(int argc, _TCHAR* argv[])
{
LIFO lifo = *new LIFO();
LIFO::Element element1 = *new LIFO::Element(1);
LIFO::Element element2 = *new LIFO::Element(2);
LIFO::Element element3 = *new LIFO::Element(3);
LIFO::Element element4 = *new LIFO::Element(4);
LIFO::Element element5 = *new LIFO::Element(5);
LIFO::Element element6 = *new LIFO::Element(6);
lifo.Push(element1);
lifo.Push(element2);
lifo.Push(element3);
lifo.Push(element4);
lifo.Push(element5);
lifo.Push(element6);
lifo.Peek(lifo.mSize);
lifo.Pop();
lifo.Pop();
lifo.Pop();
lifo.Peek(lifo.mSize);
lifo.Push(element1);
lifo.Push(element2);
lifo.Push(element3);
lifo.Push(element4);
lifo.Push(element5);
lifo.Push(element6);
lifo.Peek(lifo.mSize);
lifo.Empty();
lifo.Peek(lifo.mSize);
return 0;
}
LIFO.h
class LIFO
{
public:
unsigned int mSize;
LIFO(void)
:mSize(0)
{
mTop = nullptr;
}
~LIFO(void)
{
}
class Element
{
public:
Element* mNextElement;
int mData;
Element()
:mData(0)
,mNextElement(nullptr)
{
}
Element(int data)
:mData(data)
,mNextElement(nullptr)
{
}
~Element()
{
}
};
Element* mTop;
void Push(Element& element)
{
if(mTop != nullptr)
{
Element* newElement = &element;
newElement->mNextElement = mTop;
mTop = newElement;
delete newElement;
newElement = nullptr;
}
else
{
mTop = &element;
}
++mSize;
}
void Pop()
{
if(mTop != nullptr)
{
Element* oldElement = mTop;
mTop = mTop->mNextElement;
--mSize;
delete oldElement;
oldElement = nullptr;
}
}
void Empty()
{
while(mTop != nullptr)
{
Pop();
}
}
void Peek(unsigned int depth)
{
Element* current = mTop;
for(unsigned int i = 0; i < depth; ++i)
{
if(current != nullptr)
{
std::cout << current->mData << '\n';
if(current->mNextElement != nullptr)
{
current = current->mNextElement;
}
else
{
break;
}
}
else
{
break;
}
}
delete current;
current = nullptr;
}
};
我也曾在析构函数中尝试过这些并且它们都没有正常工作
~LIFO(void)
{
Element* current = mTop;
while(current != nullptr)
{
Element* next = current->mNextElement;
delete current;
current = next;
}
current = nullptr;
}
如何在此堆栈中安全释放内存?
答案 0 :(得分:1)
您对Peek
的理解是错误的。 Peek不会删除堆栈中的任何元素。在Peek中删除删除语句。但是界面仍然是错误的。
来推,尝试这个修改过的Push。
void Push(Element* element)
{
if(mTop != nullptr)
{
Element* currTop = mTop;
element->mNextElement = currTop;
mTop = element;
}
else
{
mTop = element;
}
++mSize;
}
现在你的课程的使用应该是
LIFO* lifo = new LIFO();
LIFO::Element* element1 = new LIFO::Element(1);
析构函数~Lifo()
中的代码很好。完成堆栈操作后,使用语句delete lifo;
删除lifo。