可能重复:
为什么使用“新”会导致内存泄漏?
我对 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