简体   繁体   English

std :: vector :: reserve失效

[英]std::vector::reserve Invalidation

If I call std::vector::reserve to reserve a certain amount of memory for my vector, will this memory remain allocated until I destroy my vector or are there any method calls (perhaps clear ) that will free my reserved memory? 如果我调用std::vector::reserve为我的向量保留一定数量的内存,那么这个内存是否会被分配,直到我销毁我的vector或者是否有任何方法调用(可能是clear )将释放我的保留内存?

Edit : I will be reusing the container a large number of times so for performance reason I want to avoid memory allocations. 编辑 :我将重复使用容器很多次,所以出于性能原因我想避免内存分配。 It is for this reason I reserve memory up front so I want to be certain I do nothing to lose the allocated memory. 正是出于这个原因,我预先保留了内存,所以我想确定我没有做任何事情来丢失分配的内存。

clear only affects the size, not the capacity. clear只影响大小,而不影响容量。 shrink_to_fit in C++11 may be what you are looking for. C ++ 11中的shrink_to_fit可能就是你要找的东西。

Edit: I will be reusing the container a large number of times so for performance reason I want to avoid memory allocations. 编辑:我将重复使用容器很多次,所以出于性能原因我想避免内存分配。 It is for this reason I reserve memory up front so I want to be certain I do nothing to lose the allocated memory. 正是出于这个原因,我预先保留了内存,所以我想确定我没有做任何事情来丢失分配的内存。

You need only to avoid two things: 你只需要避免两件事:

1. shrink_to_fit , but it is only a request to free memory, it is not a must for vector to actually do this. 1. shrink_to_fit ,但它只是一个释放内存的请求,它不是向量实际执行此操作的必要条件。

2. Only swap with empty vector will change capacity for sure (see See ideone ): 2.只有使用空向量进行swap才能确保更改容量(请参阅参见ideone ):

vector<int> v;
v.reserve(100);
vector<int>().swap(v);
ASSERT(v.capacity() == 0);

Neither pop_back , clear nor resize to smaller size will reduce vector capacity. 无论是pop_back清除还是调整大小都不会降低矢量容量。

BTW, consider to use std::array<> . 顺便说一下,考虑使用std :: array <>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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