Normally when I use STL objects that are in a non-local scope I store pointers to the data I want to store. For instance
std::vector<MyStruct*>
When it’s time to cleanup the vector I then go through and delete everything. I’ve recently noticed that this isn’t necessary like I thought it was. For whatever reason I was thinking the STL classes stored data on the stack, whereas I now think it allocates it on the heap. Is this correct? Is the only real benefit to storing objects as pointers to reduce copy time?
The standard containers allocate memory via an Allocator object, whose type is passed as a template parameter. If you’re not passing anything else, that’ll be
std::allocator<T>, which will usenewto allocate the memory.Bottom line: you can force them to allocate memory almost any way you want to, but by default it’ll come from the free store.
If you really want a container of pointers were the container will own the pointee objects, (e.g., will automatically delete them when the object is destroyed), you might want to look at Boost Pointer Containers.