←back to thread

178 points todsacerdoti | 1 comments | | HN request time: 0s | source
Show context
TonyTrapp ◴[] No.26340399[source]
Don’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.

replies(4): >>26340422 #>>26340494 #>>26340600 #>>26341355 #
pdpi ◴[] No.26340494[source]
Hence “blindly”. The blog post was a detailed, less sanctimonious version of your comment.
replies(2): >>26340514 #>>26340605 #
TonyTrapp ◴[] No.26340514[source]
But 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.

replies(2): >>26340724 #>>26340893 #
1. xKingfisher ◴[] No.26340724[source]
Given 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++.