gpt4 book ai didi

c++ - 我将如何正确存储多个实例对象?

转载 作者:行者123 更新时间:2023-11-28 03:25:23 24 4
gpt4 key购买 nike

我正在制作一个中级/高级 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;
}

我目前正在使用双端队列(最近从使用 vector 更改为),但我发现内存使用没有差异。我虽然从“评论测试”中发现我拥有的这些生成函数是内存泄漏的原因。由于这是创建/生成实例的错误方法,我想知道是否有更好的方法来存储这些对象。

tl;dr:有哪些更好的对象可以存储非常量的对象?如何存储?

最佳答案

我猜你永远不会清除 myStorage 中的新生成对象,这会导致内存增加(如你所指的内存泄漏)。如果我是正确的,你的 myStorage 声明如下:

std::deque<theObject*> myStorage;

如果您调用以下任一调用,指向 theObject 的指针将被删除,但不会删除真正动态分配的对象。

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

代码中的另一个小问题,您在 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

关于c++ - 我将如何正确存储多个实例对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14229560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com