[llvm-dev] [cfe-dev] Modernizing LLVM Coding Style Guide and enforcing Clang-tidy

Chandler Carruth via llvm-dev llvm-dev at lists.llvm.org
Thu Dec 29 14:19:52 PST 2016


Dave pointed out that I didn't complete one aspect of my argument on the
push_back vs. emplace_back:

On Thu, Dec 29, 2016 at 2:04 PM Chandler Carruth <chandlerc at gmail.com>
wrote:

> Still another way to see the consequence of this is to look at the nature
> of compiler errors when a programmer makes a mistake.
>
> With emplace_back, if you fail to call the constructor correctly, all of
> the error messages come with a layer (or many layers) of template
> instantiation. With push_back(T(...)), the constructor call is direct and
> the error messages are as well.
>
> With emplace_back, if you are converting from one type to another and the
> conversion fails, you again get template backtraces. With push_back, all
> the conversions happen before the push_back method and so the error is
> local to your code.
>

This in turn makes me prefer push_back(T(...)) over empalce_back(...). I
*like* the constructor being called explicitly in the users code if is an
*explicit* constructor. For things that should be implicit, they already
are with push_back. If the API of the type went out of its way to make a
constructor call explicit, I'd like to see the user code actually calling
it.


The consequence of this is very simple guidelines for programmers to: don't
use emplace_back unless you *must* use it. So for containers of
non-copyable and non-movable types, it can be very useful and important.
But in every other case I would rather see push_back (and if an explicit
constructor call is necessary, an explicit constructor call).

My two cents.
-Chandler
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20161229/e2ac5f9e/attachment.html>


More information about the llvm-dev mailing list