[英]c++ vector emplace_back is faster?
If I have a class 如果我有课
class foo {
public:
foo() { // spend some time and do something. }
private:
// some data here
}
Now I have a vector of foo, I want to put this vector into another vector 现在我有一个foo的向量,我想将此向量放入另一个向量
vector<foo> input; // assume it has 5 elements
vector<foo> output;
Is there ANY performance difference with these two lines? 这两条线有什么性能差异?
output.push_back(input[0])
output.emplace_back(input[0])
Is there ANY performance difference with these two lines?
这两条线有什么性能差异?
No, both will initialise the new element using the copy constructor. 不,两者都将使用复制构造函数初始化新元素。
emplace_back
can potentially give a benefit when constructing with more (or less) than one argument: 当使用一个(或少于)一个参数构造时,
emplace_back
可能会带来好处:
output.push_back(foo{bar, wibble}); // Constructs and moves a temporary
output.emplace_back(bar, wibble); // Initialises directly
The true benefit of emplace
is not so much in performance, but in allowing non-copyable (and in some cases non-movable) elements to be created in the container. emplace
的真正好处不在于性能,而是在于允许在容器中创建不可复制(有时在某些情况下不可移动)的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.