【发布时间】:2013-01-09 06:33:59
【问题描述】:
我正在制作一个中级/高级 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;
}
我目前正在使用双端队列(最近从使用向量更改),但我发现内存使用量没有差异。我虽然从“评论测试”中发现,我拥有的这些生成功能是内存泄漏的原因。由于这是创建/生成实例的错误方法,我想知道是否有更好的方法来存储这些对象。
tl;dr:有哪些更好的对象来存储非常量的对象以及如何存储?
【问题讨论】:
-
使用智能指针,忘记内存泄漏。
-
"当你需要一个(非平凡的)复制构造函数、复制赋值运算符或析构函数时,你很可能也需要实现其他的"
-
@9dan 指的是the rule of three。