push_back or emplace_back with std::make_unique
It doesn't make a difference as far as construction of the new object is concerned; you already have a unique_ptr<Foo>
prvalue (the result of the call to make_unique
) so both push_back
and emplace_back
will call the unique_ptr
move constructor when constructing the element to be appended to the vector
.
If your use case involves accessing the newly constructed element after insertion, then emplace_back
is more convenient since C++17 because it returns a reference to the element. So instead of
my_vector.push_back(std::make_unique<Foo>("constructor", "args"));
my_vector.back().do_stuff();
you can write
my_vector.emplace_back(std::make_unique<Foo>("constructor", "args")).do_stuff();
Related videos on Youtube
NHDaly
Software Engineer, Xoogler. BS, Computer Science, University of Michigan, 2013 *Profile picture source: Nedroid, http://nedroidpicturediary.apps-1and1.com/shopimages/towardstomorrow.jpg, © Anthony Clark
Updated on June 18, 2022Comments
-
NHDaly almost 2 years
Based on the answers in these questions here, I know that it is certainly preferred to use c++14's
std::make_unique
than toemplace_back(new X)
directly.That said, is it preferred to call
my_vector.push_back(std::make_unique<Foo>("constructor", "args"));
or
my_vector.emplace_back(std::make_unique<Foo>("constructor", "args"));
That is, should I use
push_back
oremplace_back
when adding anstd::unique_ptr
constructed fromstd::make_unique
?==== EDIT ====
and why? c: <-- (tiny smile)
-
Cheers and hth. - Alf about 9 yearsWith an actual argument of the vector's item type,
push_back
andemplace_back
necessarily do the same. -
dyp about 9 years
-
NHDaly about 9 years@Praetorian whoops thanks.
-
Yakk - Adam Nevraumont about 9 yearsIf you have a custom deleter on your
unique_ptr
, then things can change.
-
-
NHDaly about 9 yearsYes agreed, that's why I asked. :)
-
j b over 5 yearsActually, there is a difference...
emplace_back()
returns a reference to the added element, whereaspush_back()
returns void.emplace_back(std::make_unique<>())
is therefore useful in contexts where you need to use the object after it has been added. -
Praetorian over 5 years@JamieBullock Well, there was no difference when I answered the question 3 years ago. Updated the answer to include the C++17 change to the return type. Thanks.