简体   繁体   中英

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

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM