PSA: push_back vs emplace_back

61 views
Skip to first unread message

Greg Thompson

unread,
Sep 13, 2019, 5:35:48 AM9/13/19
to Chromium-dev
Heads-up to those who don't monitor the base channel on slack. Please reserve emplace_back in sequence containers for those times when you really are passing arguments to an object's ctor. Use push_back for times when you already have an instance of the thing you want to put in the container. To be concrete, do this:

std::vector<Foo> foos;
Foo some_foo;
foos.push_back(std::move(some_foo));

Not this:

std::vector<Foo> foos;
Foo some_foo;
foos.emplace_back(std::move(some_foo));

I've seen the latter several times recently, and it always reads wrong to me. It turns out I'm not alone.


Also see: https://abseil.io/tips/112, which suggests that push_back should mostly be preferred over emplace_back when it can be used.

Thank you.

Christian Biesinger

unread,
Sep 13, 2019, 12:58:08 PM9/13/19
to Greg Thompson, Chromium-dev
(the slack channel was apparently #base, if you were wondering but
don't want to click the link)

Christian
> --
> --
> Chromium Developers mailing list: chromi...@chromium.org
> View archives, change email options, or unsubscribe:
> http://groups.google.com/a/chromium.org/group/chromium-dev
> ---
> You received this message because you are subscribed to the Google Groups "Chromium-dev" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to chromium-dev...@chromium.org.
> To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-dev/CAKQnr0T00z%3Df27m9ae9nMWeu4TQkgPrL8EV%3D1bFJ93kOZd6tTw%40mail.gmail.com.

Joe Mason

unread,
Sep 13, 2019, 4:57:52 PM9/13/19
to Christian Biesinger, Greg Thompson, Chromium-dev

Peter Kasting

unread,
Sep 13, 2019, 5:07:24 PM9/13/19
to Joe Mason, Christian Biesinger, Greg Thompson, Chromium-dev
On Fri, Sep 13, 2019 at 1:57 PM 'Joe Mason' via Chromium-dev <chromi...@chromium.org> wrote:
I don't think it meets the bar for that, personally.

PK 
Reply all
Reply to author
Forward
0 new messages