2016-08-12 34 views
-1

我有下面的代碼,我想讓它工作得更好,速度更快。我想我應該改變擦除方法。有什麼想法嗎?我想我有內存泄漏,但我不知道要改變什麼。替代擦除功能C++更好的內存和時間節省

#include <iostream> 
#include <unordered_map> 
#include <string> 

class DocumentStorage 
{ 
    class Document 
    { 
    public: 
     Document(std::string& title, std::string& content) 
     { 
      this->title = title; 
      this->content = content; 
     } 

     std::string title; 
     std::string content; 
    }; 

public: 
    void add(int id, std::string title, std::string content) 
    { 
     storage[id] = new Document(title, content); 
    } 

    void remove(int id, std::string& title, std::string& content) 
    { 
     std::unordered_map<int, Document*>::iterator it = storage.find(id); 

     Document* doc = it->second; 
     title = doc->title; 
     content = doc->content; 

     storage.erase(it); 

    } 

    void clear() 
    { 
     storage.clear(); 
    } 

private: 
    std::unordered_map<int, Document*> storage; 
}; 

#ifndef RunTests 
int main() 
{ 
    DocumentStorage storage; 
    storage.add(123456, "Hamlet", "Hamlet, Prince of Denmark."); 
    storage.add(123457, "Othello", "Othello, the Moore of Venice."); 

    std::string title, content; 
    storage.remove(123456, title, content); 

    std::cout << title << '\n'; 
    std::cout << content; 

    storage.clear(); 
} 
#endif 
+1

更快?你有沒有測量過這個函數是你應用程序中的瓶頸? –

+0

我想讓代碼更快,我認爲問題出在代碼的那一部分。你有另一個想法嗎? –

+0

那麼,你會得到一個'Document'對象來修改它,只是在之後立即清除它?誰擁有'文檔*'?除了'存儲'以外的東西是否有其參考? – Chad

回答

2

保持的Document*集合,你已經通過新的分配,意味着你承擔責任,通過調用delete刪除它們。

最簡單的(C++ 11)固定在你的情況是你的存儲更改爲:

std::unordered_map<int, std::unique_ptr<Document>> 
0

添加某種狀態成員並在需要時啓動它。是這樣的:在你刪除功能

class Document 
{ 
    bool _inactive; // it equals false by default 
}; 

..

void remove(...) 
{ 
    ... 
    doc->setInactive(); 
} 

最後你應該聲明自己的查找功能,其會通過這些記錄,即標記爲非活動狀態。

我知道這有點奇怪,但希望它會起作用:)