Search code examples
c++pointersmemory-leaksvectordynamic-allocation

when populating an std::vector by value, will dynamically allocated object pointers be deleted?


Possible Duplicate:
Why does the use of ‘new’ cause memory leaks?

I'm fairly new to STL, and I've read that it is good practice to generally keep vectors of objects rather than vectors of pointers to objects. In an attempt to comply with that creed I ran into the following scenario:

//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;

first question: In Approach A, is a memory leak created?
second question: assuming A does produce a memory leak, does B solve it? third question: is there (or more likely, 'what is') a better way to add custom class objects (e.g. requiring dynamic allocation via 'new' or 'malloc') to a vector by value?

thanks, CCJ


Solution

  • first question: In Approach A, is a memory leak created?

    Yes.

    second question: assuming A does produce a memory leak, does B solve it?

    Yes, but it's a silly solution. And unsafe in the event that the DD_DungeonRoom's copy constructor or vector::push_back throws an exception.

    third question: is there (or more likely, 'what is') a better way to add custom class objects (e.g. requiring dynamic allocation via 'new' or 'malloc') to a vector by value?

    No objects in C++ require dynamic memory allocation. Just add objects directly to the vector calling the constructor, sans new.

    mvLayoutArray.push_back(DD_DungeonRoom());
    

    Even better, if your compiler supports the feature (it is new to C++11), would be to use emplace_back which completely bypasses any copies, and constructs your object directly in the vector. Just pass the same arguments to it as you would to your constructor. In our case, that's none:

    myLayoutArray.emplace_back();