簡體   English   中英

如何正確存儲多個實例對象?

[英]How would I store multiple instance objects correctly?

我正在制作一個中級/高級C ++程序,准確的視頻游戲。

最近我注意到有大量的內存被泄露,我想知道我創建實例的方式是否有問題。

下面是一個總結(但最初是復雜的)類:

class theObject
{
 //Instance variables
 //Instance functions
};

與此對象(與我存儲任何其他的目的,我的每一個不同的變異模板的數組索引theObject這部分不是很重要,但是我將它們存儲(或者在我看來的方式)是:

//NEWER VERSION WITH MORE INFO
void spawnTheObject()
{
 theObject* NewObj=ObjectArray[N];
 //I give the specific copy its individual parameters(such as its spawn location and few edited stats)
 NewObj->giveCustomStats(int,int,int,int);//hard-coded, not actual params
 NewObj->Spawn(float,float,float);
 myStorage.push_back(new theObject(*NewObj));
}


//OLDER VERSION
void spawnTheObject()
    {
     //create a copy of the arrayed object
     theObject* NewObj=new theObject(*ObjectArray[N]);
     //spawn the object(in this case it could be a monster), and I am spawning multiple copies of them obviously
     //then store into the storage object(currently a deque(originally a vector))
     myStorage.push_back(new theObject(*NewObj));
     //and delete the temporary one
     delete NewObj;
    }

我目前正在使用deque(最近使用向量更改)但我發現內存使用沒有區別。 我從“評論測試”中發現,我所擁有的這些產卵函數是內存泄漏的原因。 由於這是創建/生成實例的錯誤方法,我想知道是否有更好的方法來存儲這些對象。

tl; dr:有哪些更好的對象來存儲非恆定數量的對象以及如何?

我猜你永遠不會在myStorage中清除新的spawn對象導致內存增加(因為你引用內存泄漏)。 如果我是正確的,你的myStorage聲明如下:

std::deque<theObject*> myStorage;

如果您調用以下任一調用,則指向該對象的指針將被刪除,但不會刪除實際動態分配的對象。

 myStorage.pop_back();
 myStorage.clear();

您的代碼中的另一個小問題是,您在spawnTheObject()函數中進行不必要的對象分配/解除spawnTheObject()

如何用指針類型清理容器

您需要遍歷myStorage中的每個元素,刪除該對象然后清除容器,例如:

for (std::deque<theObject*>::iterator iter=myStorage.begin();
     iter != myStorage.end(); ++iter)
{
   delete (*iter);
}
myStorage.clear();

更好的方案:

std::dequestd::vector使用智能指針,然后當從STL容器中刪除元素時,指針指向的對象也會自動刪除。

 #include <memory>

 std::deque<std::shared_ptr<theObject> > myStorage;
 myStorage.push_back(std::shared_ptr<theObject>(new *ObjectArray[N]));

 mySorage.clear();  // all memories cleared properly, no worries

如果你沒有在游戲結束時從myStorage手動刪除你的對象,或者當它們需要被銷毀時,你的內存就會泄漏。

myStorage.push_back(new theObject(*NewObj));

被推入存儲的對象由您分配,因此當它需要消失時,它應該被您銷毀。

另外我不了解中間NewObj對象的需要,它不是內存泄漏,但它是一個不必要的性能成本,1分配/釋放+ 1副本。

正如Forever所提到的,最好的辦法是開始使用智能指針, std::unique_ptrstd::shared_ptr (僅限c ++ 11)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM