Search code examples
c++heap-memorystdvectorstack-memory

Stack vs Heap - Should objects inside *vector be declared as pointers?


If I use this line

std:vector<MyObject>* vec = new std::vector<MyObject>(100);
  • If I create MyObject's in the stack and add them to the vector, they remain in the stack, right ?
MyObject obj1;
vec->push_back(obj1);
  • So if it go to the stack, than MyObject's added to the vector will be gone after method ends ? What will I have inside the vector than? Garbage?

  • Should I use this instead ?:

    std:vector<MyObject*>* vec = new std::vector<MyObject*>(100);

And if so, what about objects and primitives inside each MyObject ? Should they also be dynamically created ?

Thank You


Solution

  • The std:vector as any other Standard Library container copies elements into itself, so it owns them. Thus, if you have a dynamically allocated std::vector the elements that you .push_back() will be copied into the memory managed by the std::vector, thus they will be copied onto the heap.

    As a side note, in some cases std::vector may move elements if it is safe to do so, but the effect is the same - in the end, all the elements are under std::vector's jurisdiction.