I noticed that the memory for vector is allocated dynamically. So for a local vector, where does the memory is allocate开发者_运维问答d?
f(){
vector<int> vi;
}
The vector is allocated on the stack (28 bytes on my system). The vector contents are allocated on the heap.
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.
To expand on Yacoby's answer, RAII means that when vi
goes out of scope, anything allocated with new
(inside the vector) is delete
d (in the vector's destructor). That's how you mix stack and heap allocation.
The vector
is allocated wherever the allocator
it uses decides to allocate from.
In the default case of std::allocator
, it uses ::operator new()
.
精彩评论