当按值填充std :: vector时,会动态分配对象指针吗?

CCJ*_*CCJ 2 c++ pointers memory-leaks vector dynamic-allocation

可能重复:
为什么使用'new'导致内存泄漏?

我对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;
Run Code Online (Sandbox Code Playgroud)

第一个问题:在方法A中,是否创建了内存泄漏?
第二个问题:假设A确实产生了内存泄漏,B会解决吗?第三个问题:是否存在(或更可能是"什么是")更好的方法来将自定义类对象(例如,通过'new'或'malloc'进行动态分配)按值添加到向量中?

谢谢,CCJ

Ben*_*ley 8

第一个问题:在方法A中,是否创建了内存泄漏?

是.

第二个问题:假设A确实产生了内存泄漏,B会解决吗?

是的,但这是一个愚蠢的解决方案.如果是DD_DungeonRoom复制构造函数或vector::push_back抛出异常,则不安全.

第三个问题:是否存在(或更可能是"什么是")更好的方法来将自定义类对象(例如,通过'new'或'malloc'进行动态分配)按值添加到向量中?

C++中没有对象需要动态内存分配.只需将对象直接添加到调用构造函数的向量中即可new.

mvLayoutArray.push_back(DD_DungeonRoom());
Run Code Online (Sandbox Code Playgroud)

更好的是,如果您的编译器支持该功能(它是C++ 11的新功能),那么将使用emplace_back哪个完全绕过任何副本,并直接在向量中构造您的对象.只需将相同的参数传递给构造函数即可.在我们的例子中,那是没有的:

myLayoutArray.emplace_back();
Run Code Online (Sandbox Code Playgroud)

  • @CCJ:是的,一旦你从头脑中获得Java的想法,C++就会变得更简单,更美观. (2认同)