Suppose I have a std::vector of structs. What happens to the memory if the vector is clear()’d?
std::vector<myStruct> vecs;
vecs.resize(10000);
vecs.clear();
Will the memory be freed, or still attached to the vecs variable as a reusable buffer?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The memory remains attached to the vector. That isn’t just likely either. It’s required. In particular, if you were to add elements to the vector again after calling
clear(), the vector must not reallocate until you add more elements than the 10000 as it was previously sized.If you want to free the memory, the usual is to swap with an empty vector. C++11 also adds a
shrink_to_fitmember function that’s intended to provide roughly the same capability more directly, but it’s non-binding (in other words, it’s likely to release extra memory, but still not truly required to do so).