4

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.

user2052436
  • 3,917
  • 1
  • 21
  • 38

3 Answers3

4

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.

Maxim Egorushkin
  • 125,859
  • 15
  • 164
  • 254
4

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.

Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
Useless
  • 59,916
  • 5
  • 82
  • 126
0

Yes, you understand it correctly.

Note that it is possible that your implementation actually implements vector move semantics through swap semantics, meaning that your

v = std::vector<T>();

might end up being fully equivalent to the original swap.

AnT
  • 302,239
  • 39
  • 506
  • 752