std :: vector :: emplace_back和std :: move [英] std::vector::emplace_back and std::move
问题描述
同时使用std::vector::emplace_back
和std::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屋!