Since values of noncopyable structs and enums have unique identities, they can also have
deinit
declarations, like classes, which run automatically at the end of the unique instance's lifetime.
The first thought that came to my mind after reading the above sentence from the proposal is… why give structs/enums unnatural superpowers rather than allowing classes to be move-only?
In my mind, structs/enums are like plain old values that are meant to be copied. On the other hand, classes seem well-equipped to handle the primary example in the proposal of ensuring a resource is freed. The Swift documentation even says the following:
Use classes when you need your instances to have this kind of identity. Common use cases are file handles, network connections, and shared hardware intermediaries like
CBCentralManager
.
Instead of giving structs/enums a deinit
, couldn’t we instead allow classes to be move-only? The “move-only” part would sort of be like an optimization of the class implementation: it’s still designed to be unique and passed around but because there is ever only one active reference to the class, the class could be implemented by the compiler more efficiently (i.e. not on the heap, no reference counting).