C++ 如何释放由链表实现的队列类的成员函数动态分配的内存?
我用链表实现了一个队列类,它具有函数push和pop。每次调用时,push函数都会使用new操作符动态分配一些内存。我的问题是:C++ 如何释放由链表实现的队列类的成员函数动态分配的内存?,c++,class,oop,memory,dynamic-memory-allocation,C++,Class,Oop,Memory,Dynamic Memory Allocation,我用链表实现了一个队列类,它具有函数push和pop。每次调用时,push函数都会使用new操作符动态分配一些内存。我的问题是: 如何释放推送功能分配的内存(假设未调用pop)?我写的析构函数有用吗 如果我要通过Queue*queue2=newqueue()动态创建队列对象,调用delete queue2是否会释放push函数分配的内存(假设未调用pop) 下面是我写的代码: struct ListNode { ListNode* next; int val; List
Queue*queue2=newqueue()动态创建队列对象
,调用delete queue2
是否会释放push函数分配的内存(假设未调用pop)struct ListNode {
ListNode* next;
int val;
ListNode(int x) {
val = x;
this->next = nullptr;
}
};
class Queue {
public:
Queue() {
head = nullptr;
tail = nullptr;
}
// Destructor for freeing all dynamically allocated memory
~Queue(){
if (head){
ListNode* cur = head;
ListNode* next;
// iterate through the list and free all memory
while (cur){
next = cur->next;
delete cur;
cur = next;
}
head = nullptr;
}
}
void push_front(int x) { // add node at then end of linked list
// Need to dynamically allocate front bc want it to persist after leaving this block
ListNode* front = new ListNode(x);
if (!head) {
head = front;
tail = head;
}
else {
tail->next = front;
tail = tail->next;
}
}
void pop_back() { // remove the first node of the linked list
if (!head) {
return;
}
ListNode* newHead = head->next;
delete head; // free memory
head = newHead;
}
private:
ListNode* head;
ListNode* tail;
};
int main() {
Queue queue = Queue();
queue.push_front(1);
queue.push_front(2);
}
是通常情况下,当对象被销毁时,在对象生存期内分配的内容将在析构函数中取消分配 那么回答你的第一个问题。是的,析构函数看起来做了正确的事情
未提出的问题是您的代码做得足够了。
这里的答案是否定的。问题是编译器会自动生成两个方法,这些方法在动态分配中不能很好地工作,您必须手动提供实现 因此,您的类缺少复制构造函数和复制赋值运算符。这被称为三分法则(复制构造函数/复制赋值/析构函数)
如果它是由
new
分配的,请使用delete
删除它。如果它是由new[]
分配的,请使用delete[]
删除它。你这样做了,你的析构函数看起来是正确的。你真正的问题是什么?
{
Queue a;
a.push_front(1);
Queue b(a); // Problem is here.
// The default generated copy constructor
// creates a shallow copy of the object.
}
// the destruction of the objects b and a interact resulting in
// a double de-allocation of your ListNode.