2013-11-21 27 views
0

的向量的對象時:內存泄漏刪除保持我有以下類,<code>Tuple</code>串

class Tuple { 
    public: 

    Tuple(){ 

    } 

    Tuple(vector<string> newValueList){ 
     this->values = newValueList; 
    } 

    ~Tuple() { 

    } 
    private: 

    vector<string> values; 
} 

當我調用析構函數方法我得到了內存泄漏(使用的valgrind):

Invalid read of size 8 
    at 0x40BE66: std::vector<std::string, std::allocator<std::string> >::~vector() 
    by 0x40BB2D: Tuple::~Tuple() 

我不確定爲什麼會發生這種情況。我認爲這些載體做了他們自己的記憶管理。

編輯:

下面是我如何創建一個Tuple一個例子:

Tuple* Tuple::duplicate(string value, int count, bool pull){ 
    Tuple* returnTuple = 0; 
    vector<string> newValueList; 
    for (size_t i = 0; i < this->values.size(); i++) { 
    if (((int)i == count)&&!pull) 
     continue; 
    else{ 
     newValueList.push_back(this->values[i]); 
    } 
    } 
    returnTuple = new Tuple(newValueList); 
    return returnTuple; 
} 
+1

你如何創建你的'Tuple'對象? –

+1

這個代碼本身沒有錯。 – chris

+0

雖然你不需要明確地設置'this'的值,當你在一個成員函數裏面時^^可能只是'values = newValueList'。雖然這顯然不是問題。 –

回答

0

好了,所以我想通了,你的意見後的溶液。

我有一個vector<Tuple*>,它導致內存泄漏像瘋了似的。我瀏覽了整個代碼,並將Tuple*的每個實例更改爲Tuple,並進行了其他必要的更改以確保我的代碼仍能正常工作。這樣做後,我對Tuple的析構函數沒有任何問題。感謝您的輸入。

0
Tuple* Tuple::duplicate(string value, int count, bool pull) 
  1. 什麼利用價值?

  2. 您正在分配對象動態

    returnTuple =新的元組(newValueList);

    Vector正在Tuple對象內被初始化。如果您明確地刪除代碼中某處的returnTuple,則不會有內存泄漏。您將不得不跟蹤您動態創建的所有對象。或者更好的建議是去shared_pointers,它將管理內存釋放。

由於您從動態/堆分配轉移到堆棧分配,所以還將Tuple *更改爲Tuple。一旦堆疊對象超出範圍,析構函數將自動調用。