On 2015-07-21 11:53, Thiago Macieira wrote: > On Tuesday 21 July 2015 09:09:36 Julien Blanc wrote: >> On 2015-07-20 15:26, Thiago Macieira wrote: >>> But assuming I am pushing >>> back a T, is there any reason I'd want emplace_back? Or vice-versa? >> >> emplace_back is really designed to avoid the creation of a temporary >> object, so, passing a T to it shouldn’t make any difference : that woul > > I'm asking why one of the two would be better than the other if I'm trying to > add a single T to std::vector<T>. You've explained that emplace_back is > efficient, but you haven't said whether push_back is as efficient, more > efficient or > less efficient than that. > > emplace_back will do perfect forwarding without copy direct into the vector. > Does push_back do the same?
Do you *already have* the item instance? If yes, there should be no difference; both (in an ideal implementation) should result in the item being constructed in-place using its move ctor. emplace_back is meant for when you haven't yet constructed the item. For example: std::vector<QPen> list; // less efficient auto&& pen = QPen{Qt::red, 1.5f}; list.push_back(pen); // more efficient list.emplace_back(Qt::blue, 2.0f); (Assuming that the compiler doesn't inline and copy-elide them into equivalence, anyway.) The second form avoids creation of a temporary. QPen instance is constructed in the vector in-place; no copy/move (of a QPen) occurs. (And the construction arguments are normally forwarded, so they aren't copied/moved either except for POD types for which the "copy" cost is trivial.) QPen is not an ideal example; it's most useful for large types that are expensive to construct, even by move. However, it's pretty well always going to be more efficient than constructing an object and immediately appending it to a list, even if only marginally so. -- Matthew _______________________________________________ Development mailing list Development@qt-project.org http://lists.qt-project.org/mailman/listinfo/development