c++ - Poof that shrink_to_fit or swap provide a guarantee to release vector's memory -
this question has answer here:
- c++ delete vector, objects, free memory 4 answers
can provide proof 1 of following approaches provide guarantee free vector's memory in platform independent manner?
vector<double> vec; //populating vec here
cleaning up:
1- shrink fit approach
vec.clear(); vec.shrink_to_fit();
2- swap approach
vector<double>().swap(vec);
creating vector
using new
unlikely think you'd want either.
std::vector
implementations "guarantee" allocate enough memory hold requested number of elements at minimum. latter important because asking os or runtime more memory when need grow vector expensive operation may potentially trigger element copy well. reason, lot of implementations use heuristics determine how big allocation going when vector has grow size. example, 1 implementation i'm familiar doubles size of allocation every time new memory required, giving 2^x allocation schema.
with allocation schema that, trying shrink vector from, say, 90 70 elements pretty guaranteed keep allocated memory size same reserve additional room growth.
if need exact memory allocation sizes whatever reason, you'll pretty either have use std::array
if know sizes @ compile time, or manage array yourself.
Comments
Post a Comment