by addicted · 2y ago · 0 comments
It happens to be that you can use emplace_back in place of push_back because copies and moves are just constructor overloads in C++. You shouldn't really use that, as it signals one intent, but does something else.
In the vec.push_back(Widget(a, b, c)) case the Widget is constructed first, then it gets pushed to the container. At this point the container checks if it has enough storage and expands its storage if it needs to. Then the Widget is copied/moved into the containers storage. So the ordering would be: construct, check, resize, move/copy.
While in the vec.emplace_back(a, b, c) case the container can check if it has space first before constructing the Widget directly inside the container. So the ordering would be: check, resize, construct.
So you would need some exceptionally special circumstances for this conversion from the push case to the emplace case to occur.