Say you have a simple class with some storage data structure (list, vector, queue, etc)
class MyClass
{
public:
std::list<OtherClass*> m_myList;
};
Now let’s say we allocate this class on the heap.
MyClass* pClass = new MyClass();
Now when we add more items to this list, are they on the heap or on the stack?
Example:
OtherClass* pOtherClass = new OtherClass();
pClass->m_myList.push_front(pOtherClass);
Thanks for the help!
The standard collection classes use an
Allocatorclass to allocate memory for the items being stored. The default allocator will allocate the data on the free store. You can provide your own if you want to, and I suppose if you wanted to badly enough you could have it allocate space on the stack, but you’d have to do a fair amount of extra work to make that happen.Note that you do not have to allocate the object itself on the free store to make that happen either. In fact, your
MyClass *pClass = new MyClass();is usually a poor idea. You normally just want to useMyClass Class;and be done with it. That will allocate space for the collection object itself (normally quite small) on the stack, but space for what it stores will still normally come from the free store (again, via the allocator). Among other things, this helps automate memory management — when the collection object goes out of scope, it’ll be destroyed. Its destructor will the destroy the objects it contains and release the memory (all automatically).