While reading code I see that:
vector<TypeA>(typeAObj).swap(typeAObj);
My question is
Why do they swap a vector with a copy of itself?
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.
That’s a pattern for shrink-to-fit in C++03, where there is no such operation in the interface of the vector class. What the code does is creating a copy (hopefully the
capacityof the vector will be close to the number of available elements) and then swaps it with the original vector. After the expression completes, the temporary (which now holds the original buffers) is discarded and the memory is released.Consider:
In C++11 the vector type has been modified to provide a
shrink_to_fitoperation that takes on that role. It is important to note that neither the old pattern norshrink_to_fitare binding operations, that is, there is no guarantee on thecapacityof the vector after the operation other thancapacity() >= size().