开发者

Where is the memory for a local C++ vector allocated?

开发者 https://www.devze.com 2022-12-22 13:42 出处:网络
I noticed that the memory for vector is allocated dynamically. So for a local vector, where does the memory is allocate开发者_运维问答d?

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

0

精彩评论

暂无评论...
验证码 换一张
取 消