【发布时间】:2012-12-24 00:13:12
【问题描述】:
我对 STL 还很陌生,并且我读到通常保留对象向量而不是指向对象的指针向量是一种很好的做法。为了遵守该信条,我遇到了以下情况:
//Approach A
//dynamically allocates mem for DD_DungeonRoom object, returns a pointer to the block.
//then, presumably, copy-constructs the de-referenced DD_DungeonRoom as a
//disparate DD_DungeonRoom object to be stored at the tail of the vector
//Probably causes memory leak due to the dynamically allocated mem block not being
//caught and explicitly deleted
mvLayoutArray.push_back(*(new DD_DungeonRoom()));
//Approach B
//same as A, but implemented in such a way that the dynamically allocated mem block
//tempRoom can be deleted after it is de-referenced and a disparate DD_DungeonRoom is
//copy-constructed into the vector
//obviously rather wasteful but should produce the vector of object values we want
DD_DungeonRoom* tempRoom = new DD_DungeonRoom();
mvLayoutArray.push_back(*(tempRoom));
delete tempRoom;
第一个问题:在方法 A 中,是否产生了内存泄漏?
第二个问题:假设A确实产生了内存泄漏,B解决了吗?
第三个问题:是否有(或者更有可能是“什么是”)更好的方法来将自定义类对象(例如,需要通过“new”或“malloc”进行动态分配)按值添加到向量中?
谢谢, CCJ
【问题讨论】:
标签: c++ pointers memory-leaks vector dynamic-allocation