5

Which way is better/faster in c++11 to clear a container (e.g. queue):

void clean()
{
   std::queue<int> empty_q;
   std::swap(q_to_clear, empty_q);
}

or using operator=(Q &&) (faster than swap ?)

void clean ()
{
    q_to_clear = std::queue<int>{};
}

Or is it essentially the same ?

dyp
  • 38,334
  • 13
  • 112
  • 177
GabiMe
  • 18,105
  • 28
  • 76
  • 113

2 Answers2

6

It probably makes almost no difference at all, but the move-assignment requires that the temporary source queue needs to build a new, empty state after having been moved-from, which you can avoid with the swapping. And you can write the swapping as follows:

std::queue<int>().swap(q_to_clear);
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • "...move-assignment requires that the temporary source queue needs to build a new, empty state" Um... Actually, move-assignment does not require that. A moved-from container is not guaranteed/required to become empty. – AnT stands with Russia Sep 28 '18 at 17:22
3

C++11-ness raised to extreme:

decltype(q_to_clear)().swap(q_to_clear);

Works on other std:: containers too.

and compact memory syntax is as cool as:

decltype(q_to_compact)(q_to_compact).swap(q_to_compact);
bobah
  • 18,364
  • 2
  • 37
  • 70
  • What is the use of the *compact memory* version? ... ah, you make a copy of `q_to_compact`. Would `{}` make that more clear, or are you afraid of initializer list issues? – Yakk - Adam Nevraumont Feb 02 '14 at 02:09
  • @Yakk - this is to release the excessively allocated memory. Default allocation policy for `std::vector` is to grow capacity by x2 when it is exhausted, so one may end up having half of memory wasted. So you create a temporary vector from the existing one (that vector will have the capacity exactly matching the size), swap is guts with the vector you want to compact and let it go out of scope. – bobah Feb 02 '14 at 08:59