3 ms·
Copy constructors are usually necessary when wrapping data on the heap or an OS handle. I agree this is relatively rare in user code but what’s not necessarily
by CyberRabbi 6y ago
Copy constructors are usually necessary when wrapping data on the heap or an OS handle. I agree this is relatively rare in user code but what’s not necessarily rare is having one of those types as members in an otherwise trivial type. std::string is a good example.
- zabzonk 6y ago> std::string is a good example Yeah, so USE std::string in your classes, then no copy constructors written by you will be needed. If you find yourself heap-allocating things explicitly with "new", then you are almost certainly doing something wrong.
- rrss 6y agoThis seems mostly irrelevant to the example in the post. Why does it matter who wrote the copy constructor? In the author's example, they did not write a copy constructor, they USEd std::string.
- CyberRabbi 6y agoYes but this article is not about the hazards of using new/delete. It’s about the hazards of custom copy constructors. Simply using a common type like std::string is sufficient to trigger that hazard even if you never write a custom copy constructor yourself.
- zabzonk 6y agoPerhaps you could point out the hazards? The generated code is longer, but so what, so long as it is semantically correct - longer code is not a hazard. And without knowing how the code was built, with which compiler, with which options etc. it's very hard to comment.
- roblabla 6y agoBigger ASM means you can fit less code in cache, which makes your code slower. If this happens in a hot loop, it may be the difference between "my code fits entirely in L1 cache" and "my code needs to be fetched from L2/L3". This matters in high-performance scenarios. The fact that you can introduce a performance issue simply by creating a temporary is absolutely bonkers, and makes writing high-performance code more complicated than it needs to be (and god knows it's already very complicated).
- DoofusOfDeath 6y agoDepending on the processor, it can also be the difference between instructions in a tight loop only needing to be decoded once (because of micro-op caching) vs. decoded each loop iteration.
- swolchok 6y ago> without knowing how the code was built The article links out to Compiler Explorer (https://godbolt.org/ https://godbolt.org/), which shows the exact compiler version and options and lets you play with different ones. It shouldn’t matter which compiler — the standard prohibits optimizing this.