2

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())?

mercury0114
  • 1,341
  • 2
  • 15
  • 29
  • What makes you think there is any difference betweem an object of type `T` and a string? A string is usually an object of type `std::string`, making the two equivalent. – super Nov 01 '20 at 21:33
  • @super But there is a difference between `std::string("a string")` and a string literal `"a string"` – mercury0114 Nov 01 '20 at 21:34
  • @Enrico the comment at the end of the first answer does answer **my** question, thx. – mercury0114 Nov 01 '20 at 21:36
  • 1
    Yes. And in relation to your question it is the same difference as `emplace_back(CreateClass())` and `emplace_back(10)`. – super Nov 01 '20 at 21:38
  • @super I deleted that fragment about strings. Is the question better-phrased now? – mercury0114 Nov 01 '20 at 21:47
  • There is no difference btw emplace_back and push_back when object is already constructed, no matter it is temporary or not. – Slava Nov 01 '20 at 21:50
  • @Slava one question: would any compiler be allowed to do an optimisation of the following sort: "hey, I see `CreateClass() is a temporary that will never be used again, let me avoid creating a temporary and instead make the CreateClass method populate the last vector element with the data" – mercury0114 Nov 02 '20 at 01:22

1 Answers1

2

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326