C++ Allocation – How Does Dynamic Allocation Work?

allocationc

I have a big doubt about dynamic allocation. Suppose you have a class like this:

class MyClass {
    public:
        MyClass() {}
        ~MyClass() {}
    private:
        std::vector<MyOtherClass> others;
};

If I create an instance of MyClass using new MyClass, the inner vector wil be allocated in heap or on stack?

Best Answer

Note: implementations don't have to have 'stacks' and 'heaps' but they are pretty common implementation artifacts.

If you create a "local" instance of MyClass (ie. an automatic variable) then its memory will be on the stack. The 'others' member variable will typically take up a couple of 'words' in memory (eg. a 'word' might be 32 bits); one for the vectors size variable and a pointer to dynamic memory for the vector's members. The dynamic memory will be allocated on the heap by something like malloc().