←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 #
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 #
CJefferson ◴[] No.26344237[source]
In that case, push_back to emplace_back changed the semantics (as construct + push_back made a move construction, whereas emplace_back did not).
replies(1): >>26344319 #
1. shawnz ◴[] No.26344319[source]
Good point, it doesn't seem to be any bigger of a change than the original suggestion. Perhaps they mistakenly thought nobody would call emplace_back in that way by accident.