Where is the memory for a local C++ vector allocat

2019-04-08 09:11发布

问题:

I noticed that the memory for vector is allocated dynamically. So for a local vector, where does the memory is allocated?

f(){

 vector<int> vi;
}

回答1:

The vector is allocated on the stack (28 bytes on my system). The vector contents are allocated on the heap.



回答2:

You can change how memory is allocated for STL containers with the combination of Allocator template type and the allocator object passed to the constructor.

I asked a question about how to make a vector use stack storage and got this answer. You might find it interesting.



回答3:

To expand on Yacoby's answer, RAII means that when vi goes out of scope, anything allocated with new (inside the vector) is deleted (in the vector's destructor). That's how you mix stack and heap allocation.



回答4:

The vector is allocated wherever the allocator it uses decides to allocate from.

In the default case of std::allocator, it uses ::operator new().



标签: c++ vector