c++11 clearing a container with std::swap vs opera

2020-04-07 04:35发布

问题:

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 ?

回答1:

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);


回答2:

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);


标签: c++ c++11 std