4 ms·
> Shouldn't allocation strategy be decided by the caller, not type definiton? Yes. Swift made this mistake too. Classes are always heap allocated (and passed
by ninkendo 2y ago
> Shouldn't allocation strategy be decided by the caller, not type definiton?
Yes.
Swift made this mistake too. Classes are always heap allocated (and passed by reference and refcounted) and structs are always stack allocated (and passed by value).
It makes for a super awkward time trying to abstractly define a data model: you need to predict how people will be using your types, and how they’re used affects whether you should use struct or class.
The “swifty” way to do it is to just eschew class altogether and just always use struct, but with the enormous caveat that only classes can interop with ObjC. So you end up in an awkward state where if you need to send anything to an ObjC API, it has to be a class, and once you have a lot of classes, it starts to be more expensive to hold pointers to them inside structs, since it means you need to do a whole lot of incrementing/decrementing of refcounts. Because if you have a struct with 10 members that are all classes, you need to incur 10 refcount bumps to pass it to a function. Which means you may as well make that holding type a class, so that you only incur one refcount bump. But that just makes the problem worse, and you end up with code bases with all classes, even though that’s not the “swifty” way of doing things.
Rust did it right: there’s only one way to define a piece of data, and if you want it on the heap, you put it in a Box. If you want to share it, you put it in an Arc.
- Too 2y agoC# also has exactly the same concept. "class"-types are put on the heap and get assigned by reference, while "struct"-types are assigned by copy. It always seemed weird to me. You need to know which data type you are working with when passing things around and can not adjust according to the application. For certain types from the standard library it makes sense, like datetimes you probably want always be copied. But when you work in a big team where everybody has their own style and special optimization corner case, it decays quickly.