Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector move instead of swap to empty vector and deallocate storage [duplicate]

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.

like image 449
user2052436 Avatar asked Jan 27 '23 09:01

user2052436


2 Answers

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.

like image 154
Maxim Egorushkin Avatar answered Feb 16 '23 03:02

Maxim Egorushkin


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.

like image 36
Useless Avatar answered Feb 16 '23 03:02

Useless