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
v.emplace_back()
to avoid any move.emplace_back
on a map, you can still get pair construction, causing a move, even in cases when no insertion ends up being performed: stackoverflow.com/a/20328676/560648std::map
- I've never seen that happen with astd::vector
.pair
value types. Hence my bold ;) I could have simply not posted the comment, but I was half-way through before I realised how pointless it was and... well... I don't like waste... :)v.emplace_back(Object(42));
to be able to grep for the constructor uses. Now I thought I can solve the legibility problem without performance loss by callingv.emplace_back<Object>(42);
but to my surprise this also called the move constructor. I didn't find the reason for that, any clue?