0

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());
    }
GreatDane
  • 683
  • 1
  • 9
  • 31

3 Answers3

2

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).

utnapistim
  • 26,809
  • 3
  • 46
  • 82
0

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.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
  • 3
    The first sentence is rather misleading. It will allocate a small amount of stack for a few variables to manage the array of pointers; the array itself will be dynamically allocated. – Mike Seymour Jul 29 '13 at 11:02
0

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.

zahirdhada
  • 405
  • 4
  • 14
  • Thank you for the warning. I had a similar piece of code in my project and had some trouble with the deallocation of the memory on stack. I solved the problem, but I still wanted to know how the memory is managed in such a case. The actual code was a lot different and the memory allocated in `myFunction` was later used and referenced. – GreatDane Jul 29 '13 at 10:55