←back to thread

178 points todsacerdoti | 2 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 #
beeforpork ◴[] No.26340600[source]
Actually, I am not so happy with clang-tidy: its first advice was spot-in, yes. But it should have thrown the exact same advice after the student incorrectly applied the first advised patch (by not removing the 'Widget(...)' constructor call).
replies(1): >>26343133 #
shawnz ◴[] No.26343133[source]
Wouldn't that have changed the semantics (since you're not calling the copy constructor anymore?)

The student accidentally changed the semantics by adding the extra call to the copy contstructor, and therefore Clang didn't know anymore that it could be removed

replies(2): >>26344237 #>>26344288 #
1. oleganza ◴[] No.26344288[source]
The warning was not explicit enough to ask you to remove the constructor as well as changing the method name. If it called for "hey, you can remove the constructor and emplace_back would automagically call it for you in place!" and then checked that the constructor is not spelled out there, then there would not be such issue and the tool would be 100% helpful.
replies(1): >>26344327 #
2. shawnz ◴[] No.26344327[source]
It did ask to remove the constructor as well as changing the method (note which parts are covered by tildes).

My question is, after having incorrectly only done one of those things, how could it have known that the user was only halfway though a two-part operation and didn't actually mean for it to be that way? Clang doesn't know how the code was in the past.