0

I have a program using quite a bit of storage (2.5MB) and I store it all in the stack using std::vector.

  1. Would it be a good idea to save that in the heap instead and
  2. If that is the case is it possible to use functions that take references vector& when the stored types are of vector* (as they are allocated with new)?
schajan
  • 59
  • 5
  • 1
    A `std::vector` *does* store everything you put into it on the heap. – Jesper Juhl Nov 03 '19 at 11:48
  • Does this answer your question? [When vectors are allocated, do they use memory on the heap or the stack?](https://stackoverflow.com/questions/8036474/when-vectors-are-allocated-do-they-use-memory-on-the-heap-or-the-stack) – Evg Nov 03 '19 at 12:05
  • I am happy to have this problem solved then. Thanks! – schajan Nov 03 '19 at 12:10

1 Answers1

3
  1. Unlike std::array, std::vector does not store elements inside itself, it always allocates storage on the heap (unless you use a custom allocator). Your 2.5 MB go into the heap, and only std::vector itself (a couple of pointers and the size, 12/24 bytes, typically) is allocated on the stack.

  2. You can do it:

    void foo(std::vector<T>&);
    
    std::vector<T>* vec = ...;
    foo(*vec);
    

Edit. I found a duplicate question. Voted to close this one.

Evg
  • 25,259
  • 5
  • 41
  • 83