c++heap-memorystack-memoryheap-fragmentation

Is it better to use a vector containing pointers, or a vector of values (to avoid heap fragmentation)?


I'm aware of the many articles on avoiding heap fragmentation. My question has to do with specifically what happens when we use a vector to store data:

class foo{
public:
std::vector<bar>; // Or I can have std::vector<bar*>
};

I have no problem using new or delete (I don't have memory leaks, and it is very clear to me when a bar is not used and I can call delete when necessary). But with regarding to heap fragmentation, which is better ? Does this make a stack overflow more likely ?

EDIT: I don't actually have any new information to add. I just wanted to thank everyone, and say that I've found that any question that is tagged with C++ seems to attract so many knowledgeable helpful people. Its really quite nice. Thank you.


Solution

  • The std::vector guarantees, that it's contents will be stored in continuous memory. If you store objects in your vector, then each object will be next to each other in a big chunk of memory, but if you put pointers to the vector, which point to objects created with new, then each object will be in random places in memory.

    So the first version (storing objects, not pointers) is better for both avoiding heap fragmentation and utilizing the cache.