Search code examples
c++vectormoveperfect-forwardingemplace

Is emplace_back ever better than push_back when adding temporary objects?


Suppose we want to insert an object of type T into a container holding type T objects. Would emplace be better in any case? For example:

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());
}

Is there any argument to prefer v.emplace_back(CreateClass()) rather than v.push_back(CreateClass())?


Solution

  • suppose we want to insert an object of type T into a container holding type T objects. Would emplace be better in any case?

    No; there would be no practical difference in that case.