Do I understand right that with introduction of move semantics in C++11, move can be used instead of swap-to-clear idiom in order to empty vector including storage deallocation?
std::vector<T>().swap( v );
// VS
v = std::move( std::vector<T>() );
Is the second approach guaranteed to work as the first one?
PS. As @MaximEgorushkin noted, there is no need in std::move
above since r-value is assigned.
You probably confused it with std::vector<T>(v).swap(v);
- trim the vector storage.
You do not need to call std::move
when assigning an r-value though, just
v = std::vector<T>(v);
is enough.
Just for perfect clarity, if all you want is for your vector to be empty, you can just use
v.clear();
Assuming you want it to release allocated storage, then move-assignment will work in general:
v = std::vector<T>();
(see that the documentation guarantees that the move steals the right-hand-side's allocation, which will have the desired effect).
Note the exception mentioned in the same documentation: if you have a non-propogating stateful allocator, you get an element-by-element move and no guarantee of what happens to the allocated storage.
In that case v.shrink_to_fit()
may work, although it's a quality-of-implementation issue rather than a promise. Note that in this case the old swap
technique wouldn't have worked either, so this is probably a good reason to avoid that sort of allocator.
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