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
  • 4,321
  • 1
  • 25
  • 46

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
  • 131,725
  • 17
  • 180
  • 271
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
  • 555,201
  • 31
  • 458
  • 770
Useless
  • 64,155
  • 6
  • 88
  • 132
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 stands with Russia
  • 312,472
  • 42
  • 525
  • 765