9 ms·
Don’t blindly prefer emplace_back to push_back
- deleted 6y ago[deleted]
- user-the-name 6y ago"emplace_back"? People actually looked at this and went "Yes, this is a good function name. I understand this perfectly."?
- oddeyed 6y agoIf you realise how it relates to "placement new" then it does kinda make sense. But yeah, not exactly beginner friendly!
- xKingfisher 6y agoSomething like construct_back would've maybe been a little clearer. I imagine that would have it's own issues as well though.
- IshKebab 6y agoOr just `place_back`! Why do they have to be so whimsical?
- xKingfisher 6y agoMaybe they're fans of why's guide to Ruby :) Though place_back still has the connotation of 'take this thing and put it over there' that emplace_back is actually the opposite of. Naming things really is hard.
- matheusmoreira 6y agoNaming things is very hard. Wish there was away to learn how to do it better. Reading more to acquire new vocabulary? Learning latin? I'm not really sure.
- johannes1234321 6y agoWouldn't have that the inverse effect? - The more I know about the origin and etymology the more clever words I pick, the harder it is for the ones without that knowledge? The more trivial name might be the better one.
- Deukhoofd 6y agoYeah just give everything a Latin name, your co-workers will thank you ;).
- matheusmoreira 6y agoA lot of words have latin origins though. Especially scientific jargon. Greek too.
- user-the-name 6y agoDon't insist on making names as short as humanly possible. Use more words. That's all it takes.
- MauranKilom 6y agoMy stance: You start writing some piece of code and introduce e.g. a variable or a function. Then, half a minute later, you want to actually use it. You probably forgot which exact name you gave that thing. Instead of looking it up, try to come up with the name again (this time you're in the "user" perspective, not the "creator" one). If you came up with the same name: Congratulations, you probably picked a good name! If not: Think about how the two names you picked differ. What made you sway towards one or the other in the respective contexts? Is there some subtlety that you were not aware of earlier? Is the intention still the same? Maybe you even realize that what you wrote earlier doesn't fully do what you needed. This also works on longer time scales and in reverse, of course. Occasionally I look at some older code I wrote and realize that, with a shifted frame of mind, I read/understand a function name the wrong way, even though it technically means the right thing too. Try to learn from these experiences as you make them and consider them when you're coming up with a name ("can this be misunderstood from the perspective of a user that is trying to do something that's only tangentially related?").
- dmurray 6y agoAll the simple names and most of the syntax were taken in C++98. This is one of the problems with backwards compatibility: even if everyone migrates to the new standard on its first day, so you never actually have to target the old compiler, the simplest way to do things will often be the old way. Also, in mitigation, it's not a special-purpose word for appending to vectors. They introduced "emplace" to other STL data structures at the same time, with the equivalent semantics, so it's a word you only have to learn once.
- user-the-name 6y agoI mean, this is entirely a self-inflicted problem. If you'd just use a few more words in the name, none of this would be an issue. There's nothing wrong with longer function names. They make code a lot easier to read.
- dmurray 6y agoYou'd prefer something like vec.construct_then_push_back(foo, bar)? I think it's reasonable that people would want a pithier name than that, for something you're going to use constantly.
- user-the-name 6y ago"f8" would be even shorter, but we don't use that, because it is more important that code is easy to read than quick to write.
- bregma 6y agoI think they mean `std::vector::construct_back_in_place()`. 200 character line widths will no longer be enough: 400 or 500 will be more realistic. Sacrifice readability for readability.
- user-the-name 6y agoHow many function calls do you put on a single line? Break those statements up!
- cannam 6y agoI quite like the name, not least because it accurately gives the impression of "something you will probably misunderstand".
- sillysaurusx 6y agoThis had me burst out laughing. Thanks for that perspective. I guess that's one way to solve the naming problem: just make all your names super obscure as a warning to any would-be students of the dark arts.
- kevincox 6y agoMy personal rules of naming, in order of importance are: 1. Be unique. 2. Don't be misleading. 3. Be leading. So in this case you are nailing 2 but missing out on three which I would consider a "pretty good" name. Sure, it would be nice if it was a bit more obvious (maybe construct_in_place_back?) but at least it doesn't sound like it does something else so people know to look it up.
- sesuximo 6y agoIt means put into position. Seems perfectly reasonable
- xKingfisher 6y agoNot to mention the very real risk of accidently invoking the wrong constructor. If you change the type of a vector, push_back is a good deal safer than emplace_back. Especially since many of the standard containers have many more constructors that you'd think - hello std::vector(size_type count).
- rq1 6y agoUse Phantom Types. The compiler will help you.
- codeflo 6y agoThat’s one of my favorites as well. The fact that C++ will so happily auto-convert almost anything into an integer makes it even more likely to hit this accidentally.
- xKingfisher 6y agoAnd explicit constructors won't save you from this one.
- TonyTrapp 6y agoDon’t blindly prefer emplace_back to push_back* *when using it incorrectly. The premise of of emplace_back is that you use it for calling the constructor of the object in place. Obviously it won't help you if you call a copy constructor instead. I find this article a bit pointless. Clang's suggestion was spot-on and emplace_back would have (potentially) helped if the suggestion was actually followed correctly.
- xKingfisher 6y agoIt's not bad advice. I see many code reviews that use emplace_back because it's 'faster'. Though I think the abseil article does a better job of explaining why: https://abseil.io/tips/112 https://abseil.io/tips/112 [Googler; unaffiliated with Abseil(sadly)]
- pdpi 6y agoHence “blindly”. The blog post was a detailed, less sanctimonious version of your comment.
- TonyTrapp 6y agoBut then you could write a blog post about pretty much every API misuse ever, which doesn't really seem very constructive to me. But okay, maybe it's more obvious when having worked with pre-C++11 code, where you would have killed for something like emplace_back. If you are new to the language and only know modern C++, you probably don't think much about why emplace_back exists in addition to push_back, and why it can be faster.
- xKingfisher 6y agoGiven the whole scanf/strlen thing going on, more blog posts about API pitfalls wouldn't necessarily be a bad thing. And that is basically the premise of the Abseil Tip of the week series, which are an incredible resource for learning how to work with modern C++.
- pjmlp 6y agoGiven that some schools still teach C++ with Turbo C++ for MS-DOS, one cannot expect that everyone is up to date with CppCon C++Now talks.
- rq1 6y agowidgets.emplace_back(foo, bar, baz); I honestly always thought that was the only way to use emplace_back.
- forrestthewoods 6y agoWeird article. In the first section the compiler (correctly, albeit unclearly) hints the student to write “widgets.emplace_back(foo, bar, baz);”. The author then proceeds to compare widgets.push_back(std::move(w)); versus widgets.emplace_back(std::move(w));. Wat? Why is he comparing against the thing you aren’t supposed to write? That makes no sense. The final section I can’t tell if he’s comparing compile-time or run-time. The comments make me think compile but I’m not sure? Good topic for a blog post. But it feels like this post is sloppily mixing three different ideas. Very strange.
- lgeorget 6y agoThe author explains that people he's worked with when seeing a message from the compiler telling them to use emplace_back() instead of push_back() just replace "push_back" by "emplace_back" without changing the function arguments. And since the result makes the compiler happy they don't realize that this is not what the message told them to do.
- codeflo 6y agoI’ve personally never encountered the particular misunderstanding the author dispels here, but I’m sure the post is written from bitter experience. On the one hand, I shouldn’t be that surprised: Unfortunately, programming in C++ is really brutal for people who would rather learn by example than by carefully reading documentation. But on the other hand, my instinctive reaction is: Come on, is this really something that confuses people? emplace_back is all about constructing something in-place, which is exactly the opposite of moving it there! How can any professional programmer be 180 degrees wrong about the purpose of a function they use regularly? What I want to say here is that C++ is really hard, and that there are a million subtle things that one simply has to look up instead of making educated guesses. I don’t think people appreciate this difficulty enough.
- mettamage 6y agoI learn C++ by example by using the VSCode debugger. I prefer it over gdb with tui. It won’t go all the way (e.g. educational/smallish projects only that are single threaded) but by that time a programmer has seen some wonky things happening that they can hypothesize about. In my case: - dangling pointers - integer under/overflow - macro expansion (not via debugger but VSCode helps with this) - double values not being the same when you expect them to be the same - Seeing if something is copied or moved [1] [1] Not sure if this is actually true. But I think it can be true by simply stepping inside the function like emplace_back
- gurkendoktor 6y agoMy pet peeve with all emplace functions, make_unique etc. is that CLion won't let you command-click the calls to jump into the constructor being called. Are other IDEs better at this?
- kevincox 6y agoThis would be very hard to do because the code isn't explicitly calling the constructor. It just happens to be passing arguments which get passed to a constructor. I guess with a fancy set of heuristics or special-casing std:: it could work.
- posharma 6y agoThis (https://abseil.io/tips/112 https://abseil.io/tips/112) is a much better explanation of this advice.
- jokoon 6y agoThanks for the article, there should be a huge list of those type of classic C++ misconceptions/FAQ style. One of my favorite is "you don't need a linked list". Although I'm still genuinely interested when a linked list is best suited. I'm also curious why they were invented and why they're taught, maybe just for teaching purposes...
- quietbritishjim 6y agoI used one the other day because it had the interface I needed and the number of items was so small and so infrequently iterated over that performance didn't matter. (I guess that's not really what you meant though: you were probably interested in a use where it really was needed for performance reasons - splicing things around or the like.) Specifically I needed the guarantee that iterators weren't invalidated by other parts of the list changing. I could've used a vector and worked around it but it would've taken more effort and more code, and like I said the performance difference wouldn't have made an overall difference to the program.
- beaconstudios 6y agoNaively, I would assume that LLs are best used for long lists which are typically traversed incrementally, like a FILO-only job queue. That wouldn't perform better than a static array of statically-sized objects, but it could be better for eg. a list of structs with flexible array members (ie, variable-sized structs). They might be good for traversed lists with the possibility of partway insertion too, or performing insertion sort. Hell they might even be good for traversed lists in the general case, but I'm not a low level dev so I don't know without testing it. Fun exercise though! I'm guessing they're taught because they're taught, in that special inertial way that education propagates. Originally, I bet they were introduced when implementing your own data structures rather than pulling a library was normal industry practice. Of course there is tons of value in knowing about data structures and their characteristics, but probably not in knowing how to implement LLs.
- gmueckl 6y agoEven if linked lists and double linked lists aren't all that universally useful by themselves, they teach all the basics about taversing data structures by references / pointers that more complex trees and graphs require. A linked list is just a degenerate tree with at most one child for each parent. So I think teaching that isn't a bad decision.
- choeger 6y agoWhy is there no move_back(), I wonder?
- lgeorget 6y agoWell that's emplace_back() or push_back() when you pass them a r-value reference basically.
- pornel 6y agoRust's push is a `move_back`. Curiously, it doesn't have any equivalent of emplace or placement new. It does memcpy on push, and relies on the optimizer to remove it.
- __s 6y agoRust gets away with this because it doesn't have move constructors. Which is a pain if you want self referencing structures, but avoids quite a bit of complexity
- sillysaurusx 6y agoLazy HN: Is emplace_back new? I was a C++ dev for over a decade and never came across it. But I got out of serious gamedev in 2014 or so (sadly). (Is this what it feels like to become a dinosaur?) There is some confusion on this issue: https://stackoverflow.com/questions/4303513/push-back-vs-emplace-back https://stackoverflow.com/questions/4303513/push-back-vs-emp... The function void emplace_back(Type&& _Val) provided by MSCV10 is non conforming and redundant, because as you noted it is strictly equivalent to push_back(Type&& _Val). Looks like (as usual) MSVC's lackluster implementation drives real-world usage. Is there a rule of thumb?
- gpderetta 6y agoIt was added in C++11 as part of the perfect forwarding changes, so I would say that it is about a decade old. As an aside, if you check cppreference.com it will tell you which standard added (or removed) a specific API.
- MauranKilom 6y agoRandom emplace_back hate: I really dislike how you can't use it for objects that you'd normally use aggregate initialization for. See https://godbolt.org/z/6qW7q3 https://godbolt.org/z/6qW7q3 struct SimpleData { int a; double b; }; SimpleData someData = {1, 2.0}; // ok std::vector<SimpleData> data; // Why can I not do this? data.emplace_back(1, 2.0);
- Koshkin 6y agoTo be fair, push_back won’t help you here, either.
- MauranKilom 6y agoIt does, actually. In fact, this is the most concise one (see godbolt link): data.push_back({1, 2.0}); That does not work with emplace_back (not that it would be useful) because the template arguments can't be deduced from the initializer list (whereas for push_back the type is known so you can initialize it with the initializer list).
- Koshkin 6y agoYou are correct, the problem is exclusively with emplace_back; incidentally, there is an "official" discussion of this at https://cplusplus.github.io/LWG/issue2089 https://cplusplus.github.io/LWG/issue2089.
- vinkelhake 6y agoYou can as of C++20 - aggregate initialization has been extended to support T(x, y) syntax. See https://godbolt.org/z/Tj5baM https://godbolt.org/z/Tj5baM and https://en.cppreference.com/w/cpp/language/aggregate_initialization https://en.cppreference.com/w/cpp/language/aggregate_initial... (case 5).
- gpderetta 6y agoThat's because of the epic fail that are initializer lists that prevent aggregate initialization (which is otherwise awesome) to be used safely in generic contextes.
- kzrdude 6y agoBut, it seems like no harm done? So it's just a code style issue.
- jedimastert 6y ago> C++ is really brutal for people who would rather learn by example than by carefully reading documentation. I've been at my current job for a little over two years. Before then I never touched C++; now it's the main (basically only) language used here. I'm still getting trucked by this...
- justicezyx 6y agoGoogle's internal style guide basically had this same suggestion. Was it publicized already? If so, please dont down vote me. Just a hint that this is a very sound suggestion.