简体   繁体   中英

Stack VS Heap with Classes

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!

std::list存储到堆上的元素,因此您的类不在哪里都无所谓。

The standard collection classes use an Allocator class 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 use MyClass 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).

The default allocator for the standard template classes allocate on the heap, no matter what. So, they would be on the heap.

The simple rule: If you're allocating new OtherClass objects with new , then they are on the heap. new only allocates memory from the heap. (Exception: If you use a custom allocator, which is an advanced C++ feature, they can be in whatever memory area of your choosing.)

Your m_myList is an instance of std::list , which happens to also store its internal information on the heap (but that is an implementation detail and you usually don't need to worry about it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM