假设我们要将一个类型为 T 的对象插入到保存类型为 T 的对象的容器中。无论如何,emplace 会更好吗?例如:
class MyClass {
MyClass(int x) { ... }
}
MyClass CreateClass() {
int x = ... // do long computation to get the value of x
MyClass myClass(x);
return myClass;
}
int main() {
vector<MyClass> v;
// I couldn't benchmark any performance differences between:
v.push_back(CreateClass());
// and
v.emplace_back(CreateClass());
}
有什么更喜欢的理由 v.emplace_back(CreateClass())
而不是 v.push_back(CreateClass())
?
最佳答案
suppose we want to insert an object of type T into a container holding type T objects. Would emplace be better in any case?
没有;在这种情况下,不会有任何实际差异。
关于c++ - 添加临时对象时 emplace_back 是否比 push_back 更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64637192/