Question

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());
    }
Was it helpful?

Solution 2

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.

OTHER TIPS

A std::vector needs to be able to change it's allocated data, which means it will keep an allocated array (an (A*)[] in this case) internally. This array will be allocated on the heap (dynamically).

This will cause memory leaks every time myFunction() is called. The variable aarray is local to myFunction() and is allocated statically, hence it is destroyed as soon as the control returns from the function. However, the two objects of class A are created dynamically, and are not destroyed automatically by C++. You have to use delete to delete these objects. You have not deleted the objects in your code, so these two objects will remain unreferenced in memory, causing a memory leak.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top