why does vector.emplace_back call the move-constructor?
c++, vector
Solution
`emplace_back` forwards its arguments to the constructor of the vector element class, called in-place on the next available position of the `vector`.
v.emplace_back(Object{});
is sort of equivalent to:
{
Object tmp;
v.emplace_back(std::move(tmp));
}
That's why you are getting a regular constructor call followed by a move constructor call. If you want to append a new object with `emplace_back`, just call:
v.emplace_back();
Just for the sake of completeness, another reason why `emplace_back` might call a move constructor is: `emplace_back` may cause the `vector` to grow, and thus move its initial contents to their new memory location. This is not the problem here, because calling `reserve` guarantees enough capacity, but generally it's an answer to the question.
Problem
``` struct Object { Object() { cout << "constructor\n"; } Object(const Object &) { cout << "copy constructor\n"; } Object(Object &&) { cout << "move constructor\n"; } }; int main() { vector<Object> v; v.reserve(10); v.emplace_back(Object{}); } ``` This gives me the following output: constructor move constructor Why? I thought that emplace_back does create the Object in place, so that no copy or move constructors have to be called. From the description: The element is constructed in-place, i.e. no copy or move operations are performed. EDIT: Ah, okay, it seems that I fundamentally misunderstood emplace_back(). You don't have to have the Object as an argument, since it is automatically created in place for you. You only have to give the arguments for the Object-constructor to emplace_back(). So, if I had a new constructor like this: ``` Object(int) { cout << "int constructor\n"; } ``` I would call emplace_back like this: ``` v.emplace_back(42); ``` instead of this: ``` v.emplace_back(Object(42)); ``` Makes sense now, thanks a lot! EDIT2: I wish I could accept all of your answers! :-P