Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++11 clearing a container with std::swap vs operator=(T&&)

Tags:

c++

std

c++11

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 ?

like image 463
GabiMe Avatar asked Feb 01 '14 20:02

GabiMe


People also ask

What does std :: swap do?

The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables. Parameters: The function accepts two mandatory parameters a and b which are to be swapped. The parameters can be of any data type.

How do I remove all elements from a queue in CPP?

deque::clear() The clear() function is used to remove all the elements of the deque container, thus making its size 0.

How do you change queue in C++?

queue::swap() in C++ STL queue::swap() swap() function is used to exchange the contents of two queues but the queues must be of same type, although sizes may differ. Syntax: queue1. swap(queue2) OR swap(queue1, queue2) Parameters: queue1 is the first queue object.


2 Answers

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);
like image 175
Kerrek SB Avatar answered Oct 13 '22 10:10

Kerrek SB


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);
like image 34
bobah Avatar answered Oct 13 '22 10:10

bobah