std :: vector :: emplace_back和std :: move [英] std::vector::emplace_back and std::move

查看:473
本文介绍了std :: vector :: emplace_back和std :: move的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时使用std::vector::emplace_backstd::move有什么优势吗?还是因为std::vector::emplace_back会进行就地构造而只是多余?

Is there any advantage of using std::vector::emplace_back and std::move together? or it is just redundant since std::vector::emplace_back will do an inplace-construction?

需要澄清的情况:

std::vector<std::string> bar;

第一

bar.emplace_back(std::move(std::string("some_string")));

第二:

std::string str("some_string");
bar.emplace_back(std::move(str));

第三:

bar.emplace_back(std::move("some_string"));

推荐答案

在第二个版本中,有一个优势.使用std::move时,调用emplace_back将调用std::string的move构造函数,该构造函数可以保存在副本中(只要该字符串未存储在SSO缓冲区中).请注意,在这种情况下,这与push_back基本上相同.

In the second version, there is an advantage. Calling emplace_back will call the move constructor of std::string when std::move is used, which could save on a copy (so long as that string isn't stored in a SSO buffer). Note that this is essentially the same as push_back in this case.

std::move是不必要的,因为该字符串已经是prvalue.

std::move in the first version is unnecessary, as the string is already a prvalue.

std::move无关紧要,因为无法从字符串文字中移出.

std::move in the third version is irrelevant, as a string literal cannot be moved from.

最简单,最有效的方法是:

The simplest and most efficient method is this:

bar.emplace_back("some_string");

这不需要任何不必要的std::string构造,因为文字可以完美地传递给构造函数.

That requires no unnecessary std::string constructions as the literal is perfect-forwarded to the constructor.

这篇关于std :: vector :: emplace_back和std :: move的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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