3 ms·
> I had an array of widgets. Those widgets had textures. Those textures were copied over and over and over again, because containers can do that, so I had to go
by _yosefk 11y ago
> I had an array of widgets. Those widgets had textures. Those textures were copied over and over and over again, because containers can do that, so I had to go back to rethinking the storage class for the widgets.
Actually, he didn't have to rethink it, and many people don't - instead, their code just copies things. Avoiding copying increases the chance for mishandling ownership and deleting a still-used object (or you can use shared_ptr, an then at some point the reference counting involved might get slower than the overhead of gc.) Beating gc in terms of memory footprint and speed without adding bugs is possible, but not necessarily trivial - and it's often very easy to lose to gc instead.
There are many good reasons why no language ever copied C++'s approach to "values" and "references", where every type can be passed either by value or by reference and redefine copying, assignment and now "move semantics." The proliferation of unnecessary copying is one of those reasons.
- 72deluxe 11y agoPerhaps he should have put the textures in a central container and have the widgets use a reference to the texture item? I would think that adding textures as a child of the widgets would imply that he WANTED the textures copying. I wouldn't put child items into an object unless I wanted them copying too, as their lifetime is tied up with their parent object. The problem is not containers - it is more with his design and him wanting to control the lifetimes of child textures.
- _yosefk 11y agoWell, define "problem." Naive, correct C++ code will copy objects because it's the simplest way to make sure each object has one obvious owner and won't leak without having to write memory management code or fiddling with smart pointers, which have non-trivial semantics. Yeah, you can avoid the copying, but C++ definitely encourages it in the sense of making it the path of the least resistance.