Why would I ever use push_back instead of emplace_back?



C++11 vectors have the new function emplace_back. Unlike push_back, which relies on compiler optimizations to avoid copies, emplace_back uses perfect forwarding to send the arguments directly to the constructor to create an object in-place. It seems to me that emplace_back does everything push_back can do, but some of the time it will do it better (but never worse).

What reason do I have to use push_back?

David Stone

Posted 2012-06-05T02:01:45.517

Reputation: 11 983



I have thought about this question quite a bit over the past four years. I have come to the conclusion that most explanations about push_back vs. emplace_back miss the full picture.

Last year, I gave a presentation at C++Now on Type Deduction in C++14. I start talking about push_back vs. emplace_back at 13:49, but there is useful information that provides some supporting evidence prior to that.

The real primary difference has to do with implicit vs. explicit constructors. Consider the case where we have a single argument that we want to pass to push_back or emplace_back.

std::vector<T> v;

After your optimizing compiler gets its hands on this, there is no difference between these two statements in terms of generated code. The traditional wisdom is that push_back will construct a temporary object, which will then get moved into v whereas emplace_back will forward the argument along and construct it directly in place with no copies or moves. This may be true based on the code as written in standard libraries, but it makes the mistaken assumption that the optimizing compiler's job is to generate the code you wrote. The optimizing compiler's job is actually to generate the code you would have written if you were an expert on platform-specific optimizations and did not care about maintainability, just performance.

The actual difference between these two statements is that the more powerful emplace_back will call any type of constructor out there, whereas the more cautious push_back will call only constructors that are implicit. Implicit constructors are supposed to be safe. If you can implicitly construct a U from a T, you are saying that U can hold all of the information in T with no loss. It is safe in pretty much any situation to pass a T and no one will mind if you make it a U instead. A good example of an implicit constructor is the conversion from std::uint32_t to std::uint64_t. A bad example of an implicit conversion is double to std::uint8_t.

We want to be cautious in our programming. We do not want to use powerful features because the more powerful the feature, the easier it is to accidentally do something incorrect or unexpected. If you intend to call explicit constructors, then you need the power of emplace_back. If you want to call only implicit constructors, stick with the safety of push_back.

An example

std::vector<std::unique_ptr<T>> v;
T a;
v.emplace_back(std::addressof(a)); // compiles
v.push_back(std::addressof(a)); // fails to compile

std::unique_ptr<T> has an explicit constructor from T *. Because emplace_back can call explicit constructors, passing a non-owning pointer compiles just fine. However, when v goes out of scope, the destructor will attempt to call delete on that pointer, which was not allocated by new because it is just a stack object. This leads to undefined behavior.

This is not just invented code. This was a real production bug I encountered. The code was std::vector<T *>, but it owned the contents. As part of the migration to C++11, I correctly changed T * to std::unique_ptr<T> to indicate that the vector owned its memory. However, I was basing these changes off my understanding in 2012, during which I thought "emplace_back does everything push_back can do and more, so why would I ever use push_back?", so I also changed the push_back to emplace_back.

Had I instead left the code as using the safer push_back, I would have instantly caught this long-standing bug and it would have been viewed as a success of upgrading to C++11. Instead, I masked the bug and didn't find it until months later.

David Stone

Posted 2012-06-05T02:01:45.517

Reputation: 11 983


push_back always allows the use of uniform initialization, which I'm very fond of. For instance:

struct aggregate {
    int foo;
    int bar;

std::vector<aggregate> v;
v.push_back({ 42, 121 });

On the other hand, v.emplace_back({ 42, 121 }); will not work.

Luc Danton

Posted 2012-06-05T02:01:45.517

Reputation: 30 218

44Note that this only applies to aggregate initialization and initializer-list initialization. If you would be using {} syntax to call an actual constructor, then you can just remove the {}'s and use emplace_back. – Nicol Bolas – 2012-06-05T02:30:15.813

Dumb question time: so emplace_back can't be used for vectors of structs at all? Or just not for this style using literal {42,121}? – Phil H – 2012-06-05T06:31:00.740

1@LucDanton: As I said, it only applies to aggregate and initializer-list initialization. You can use {} syntax to call actual constructors. You could give aggregate a constructor that takes 2 integers, and this constructor would be called when using {} syntax. The point being that if you're trying to call a constructor, emplace_back would be preferable, since it calls the constructor in-place. And therefore doesn't require the type to be copyable. – Nicol Bolas – 2012-06-05T13:04:30.600

Why std::initializer_list&lt;int&gt;? I do not think that emplace_back({ anything here }) ever works. – Johannes Schaub - litb – 2012-06-05T21:38:26.910

@NicolBolas Ah, I got confused by your use of "this only applies": what does this refer to? (Similarly what's "it" in "it only applies"?) What I value in push_back is not that it's possible to use uniform initialization for some cases, it's that it's reliable whether e.g. the value type is an aggregate or not, as you mention. – Luc Danton – 2012-06-05T21:48:28.620

Fixed some confusion regarding passing { a, b, c } to function templates. – Luc Danton – 2012-06-05T21:49:31.757

@NicolBolas: I don't think push_back requires the type to be copyable in C++11, does it? – Mehrdad – 2013-06-29T03:43:35.690

std::tuple would allow use of emplace_back in this case – paulm – 2014-07-29T10:05:50.720

@NicolBolas So the only reason to ever use push_back is "aggregate initialization and initializer-list initialization"? Since that's not exactly the same as "uniform initialization", shouldn't this answer be modified? – Jon – 2014-07-31T12:12:08.483


This was viewed as a defect in the standard, and has been resolved. See https://cplusplus.github.io/LWG/lwg-active.html#2089

– David Stone – 2016-04-28T15:49:49.290


Backwards compatibility with pre-C++11 compilers.


Posted 2012-06-05T02:01:45.517

Reputation: 126 144

1This is the reason. – Scott – 2013-05-11T03:50:36.647

17That seems to be the curse of C++. We get tons of cool features with each new release, but a lot of companies are either stuck using some old version for the sake of compatibility or discouraging (if not disallowing) use of certain features. – Dan Albert – 2013-07-06T10:37:36.570

@DanAlbert: Not sure why it's a curse. Why use a new feature when the old one is sufficient? – Mehrdad – 2013-11-12T10:07:56.237


@Mehrdad: Why settle for sufficient when you can have great? I sure wouldn't want to be programming in blub, even if it was sufficient. Not saying that's the case for this example in particular, but as someone who spends most of his time programming in C89 for the sake of compatibility, it's definitely a real problem.

– Dan Albert – 2013-11-13T22:14:51.757

1@DanAlbert: I wasn't making a general statement, I was just talking about push_back lol. – Mehrdad – 2013-11-13T22:17:27.160

3I don't think this is really an answer to the question. To me he's asking for use-cases where push_back is preferable. – Mr. Boy – 2015-11-03T16:12:59.137

2@Mr.Boy: It's preferable when you want to be backward-compatible with pre-C++11 compilers. Was that unclear in my answer? – Mehrdad – 2016-07-18T09:27:37.540

4This has gotten way more attention than I've expected, so for all of you reading this: emplace_back is not a "great" version of push_back. It's a potentially dangerous version of it. Read the other answers. – Mehrdad – 2017-08-19T20:51:14.990


Some library implementations of emplace_back do not behave as specified in the C++ standard including the version that ship with Visual Studio 2012, 2013 and 2015.

In order to accommodate known compiler bugs, prefer usingstd::vector::push_back() if the parameters reference iterators or other objects which will be invalid after the call.

std::vector<int> v;
v.emplace_back(v[0]); // Produces incorrect results in some compilers

On one compiler, v contains the values 123 and 21 instead of the expected 123 and 123. This is due to the fact that the 2nd call to emplace_back results in a resize at which point v[0] becomes invalid.

A working implementation of the above code would use push_back() instead of emplace_back() as follows:

std::vector<int> v;

Note: The use of a vector of ints is for demonstration purposes. I discovered this issue with a much more complex class which included dynamically allocated member variables and the call to emplace_back() resulted in a hard crash.


Posted 2012-06-05T02:01:45.517

Reputation: 1 292

7This is more important than the selected answer! – balki – 2015-03-03T22:01:17.937

Wait. This appears to be a bug. How can push_back be different in this case? – balki – 2015-03-03T22:22:13.777

11The call to emplace_back() uses perfect forwarding to perform construction in place and as such v[0] is not evaluated until after the vector has been resized (at which point v[0] is invalid). push_back constructs the new element and copies/moves the element as needed and v[0] is evaluated prior to any reallocation. – Marc – 2015-03-06T16:01:19.560

Can you give an example of a compiler where you see this behaviour? I can't reproduce this problem. I suspect what you actually saw is the reference to v[0] being invalidated when the vector reallocated. – cdyson37 – 2015-03-31T15:08:42.093

@cdyson37 The described behavior was observed using Visual Studio 2012 compiler version 11 update 4. – Marc – 2015-04-07T19:02:08.357

@David - Although the new space must exist before the old is destroyed, I don't think that there are any guarantees regarding when the parameter of emplace_back is evaluated. Perfect forwarding enables delayed evaluation. It is my observation that the old vector iterators become invalid before the parameter is evaluated in the compile on which I tested and the details are largely implementation dependent. – Marc – 2015-08-06T19:23:25.703

1@Marc: It is guaranteed by the standard that emplace_back works even for elements inside the range. – David Stone – 2015-08-07T00:28:01.683

@Marc why v[0] is not evaluated until after the vector has been resized? could you describe it in detail? – camino – 2015-12-10T20:05:06.480

@DavidStone: Could please provide a reference to where in the standard this behavior is guaranteed? Either way, Visual Studio 2012 and 2015 exhibit incorrect behavior. – Marc – 2015-12-11T21:30:52.857

4@cameino: emplace_back exists to delay evaluation of its parameter to reduce unnecessary copying. The behavior is either undefined or a compiler bug (pending analysis of the standard). I recently ran the same test against Visual Studio 2015 and got 123,3 under Release x64, 123,40 under Release Win32 and 123,-572662307 under Debug x64 and Debug Win32. – Marc – 2015-12-11T21:38:07.027