c++memory-managementdynamic-allocationstatic-allocation

Where will the memory be allocated in the following piece of code?


If I declare a std::vector<A *>, where will the memory be allocated? I know new dynamically allocates memory, but the memory for the vector should be allocated statically. I want to know what happens with the memory.

    typedef std::vector<A *> AArray;

    void myFunction()
    {
        AArray aarray;
        aarray.push_back(new A());
        aarray.push_back(new A());
    }

Solution

  • AArray aarray; will allocate memory on the stack for your vector.

    aarray.push_back(new A()); Will construct an A on the heap and then return a pointer to it that will be placed in your container.