c ++ 11使用std :: swap vs operator =(T&&)清除容器 [英] c++11 clearing a container with std::swap vs operator=(T&&)

查看:51
本文介绍了c ++ 11使用std :: swap vs operator =(T&&)清除容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

或使用operator =(Q&&)(比swap更快? )

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

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

还是基本相同?

推荐答案

它可能几乎没有任何区别,但是移动分配要求临时源队列从移出后需要建立一个新的空状态,您可以通过交换来避免这种情况。您可以按如下方式编写交换:

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

这篇关于c ++ 11使用std :: swap vs operator =(T&amp;&amp;)清除容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆