I've seen some C++ code like this:
std::vector<int> vec;
vec.clear();
vec.push_back(42);
What is the purpose (if any) of clearing the vector right after creating it?
The vector (like all standard containers) owns the objects inside it. So it is responsible for destroying them. Note: If you vector contains pointers then it owns the pointers (not what the pointers point at). So these need to be deleted.
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
The standard mandates that the capacity does not change with a clear as reserve guarantees that further adding of elements do not relocate until the requested capacity is reached. This directly enforces clear to not reduce the capacity.
The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.
It serves no purpose - the vector is already created in an empty state.
If you are lucky, your compiler will optimize away this redundant call entirely - recent versions of both gcc and clang do exactly that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With