[英]C++ deleting pointer to interface vector memory leak
使用:CodeBlocks 13.12,GNU GCC mingw32-g ++,Dr.Memory
因此,我分配了一個向量隊列(先進先出)。 我編寫了程序,一切正常,但是在分配過程中,我們需要使用接口IQueue。 此界面無法更改。
#ifndef IQUEUE_H
#define IQUEUE_H
template <typename T>
class IQueue {
public:
virtual void enqueue(const T& element) = 0;
virtual T dequeue() = 0;
virtual T front() const = 0;
virtual bool isEmpty() const = 0;
};
#endif
這是我的Queue.h的(部分)信息,只為您獲得圖片。
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
#include <string>
#include <stdexcept>
#include "iqueue.h"
using namespace std;
template <typename T>
class Queue : virtual public IQueue<T> {
public:
Queue();
Queue(int capacity);
Queue(int capacity, int capacity_increment);
~Queue();
Queue(const Queue<T> &original);
void operator=(const Queue<T> &original);
void enqueue(const T& element);
T dequeue();
T front() const;
bool isEmpty() const;
private:
T *items;
int nr_of_items;
int capacity;
void expand(); //expands the array if the nr_of_items is bigger than capacity
void freeMemory();
};
/*stuff*/
template<typename T>
Queue<T>::~Queue() {
this->freeMemory();
}
template<typename T>
void Queue<T>::freeMemory() {
delete[] this->items;
}
我在operator =中使用了freeMemory(),這就是為什么它是一個單獨的函數。
所以現在主要
#include "iqueue.h"
#include "queue.h"
int main() {
IQueue<string> *sq = new Queue<string>();
/*Do stuff with the queue*/
IQueue<string> *sq2 = new Queue<string>();
sq2 = sq;
IQueue<int> *iq = new Queue<int>();
/*Do stuff with the queue*/
IQueue<int> *iq2 = new Queue<int>();
iq2 = iq;
/*how to delete?*/
return 0;
}
我測試過的東西:
刪除平方;刪除平方;刪除智商; 刪除iq2; 在freeMemory()中使用cout根本不會運行。
和以前一樣,但是我測試了在IQueue中創建虛擬解構函數。 在freeMemory()中使用cout時,它將運行一次,然后崩潰。 我得到4個無法訪問的訪問,2個無效的堆參數,2個內存泄漏。 真的不明白這里會發生什么。
我們還沒有使用uniqe指針,但是當我在google周圍搜索時,建議將其作為一種好方法。 但是我需要為我的程序提供一個很好的解釋,以了解如何執行此操作。
嘗試過vector :: erase cplusplus.com鏈接 。 感覺像這樣是正確的方法,但是我只是收到有關“在沒有模板類的情況下使用矢量擦除”的錯誤。 我包括了<vector>。
任何能將我指向正確方向的答案都值得贊賞。 關於為什么我嘗試的東西不起作用的一般信息會很好,並且可以使我更好地理解。 如果需要,我將在其中編輯更多代碼。
旁注:有人告訴您,如果在這樣的函數中應該存在try catch異常,則將throw(...)放在.h文件中:virtual T dequeue()throw(…)= 0; 但是我只是出錯了,這是標准的做法嗎?
我注意到您的代碼和要點有以下幾點:1)您正在使用指針。 也就是說,您實際上是在將一個指針分配給另一個指針。 因此,operator =()將不會被調用。 內存將在那里泄漏。 2)正如您在第一點所說的那樣,您要先刪除sq然后刪除sq2,這兩個都指向相同的內存。 因此檢測到堆損壞。 iq和iq2也會發生同樣的情況。 3)還要使用虛擬析構函數。
IQueue<string> *sq = new Queue<string>();
IQueue<string> *sq2 = new Queue<string>();
sq2 = sq;
第一次內存泄漏。 您會丟失指向sq2對象的指針。
IQueue<int> *iq = new Queue<int>();
IQueue<int> *iq2 = new Queue<int>();
iq2 = iq;
第二次內存泄漏。 同上。
現在,如果刪除指向iq1或iq2的指針,則將發生第三次泄漏,因為您的接口沒有虛擬析構函數,因此將不會調用實現中的析構函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.