添加临时对象时 emplace_back 是否比 push_back 更好?
Is emplace_back ever better than push_back when adding temporary objects?
假设我们要将一个类型为T 的对象插入到一个装有类型为T 的对象的容器中。在任何情况下都会更好吗?例如:
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?
没有;在那种情况下没有实际区别。
假设我们要将一个类型为T 的对象插入到一个装有类型为T 的对象的容器中。在任何情况下都会更好吗?例如:
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?
没有;在那种情况下没有实际区别。