Up until now I’ve almost exclusively seen the concept of noncopyable types praised for the potential they unlock for highly performant code, but while reading this latest pitch I was intrigued to see the parallels drawn between these new types and reference types.
Could there be some very valid use cases for noncopyable types in the realm of replacing some uses of classes, even if performance is of no concern in the domain?
I'm not sure if a comparison to reference types is suitable. In fact, I'd use non-copyable types in places where I want a behavior opposite to reference types: no reference semantics, in-place updates, a compile-time guarantee that no one else can access this value at the same time.
A valid use case for me is a file handle abstraction. Maybe in some scenarios it's ok for a file handle to have multiple owners, but I think in the majority of them you want only one thing to write to a file at a time. With non-copyable types this can be statically enforced, and that makes it much easier to reason about without having to think about multi-threading synchronization, reentrancy and all other consequences that fall out from concurrent file access.
Speaking of concurrency, I hope that non-copyable types can still be
Sendable, so one could transfer ownership of non-copyable values between tasks/executors.
In summary: reference types express shared ownership, non-copyable types express exclusive ownership.
I think the idea of reference type instances having unique identities is a pretty fundamental concept, and that also applies to values of noncopyable types.
Right, this is what I’m getting at.
I know that noncopyable types are very much not reference types, but because of the parallels (specifically this one mentioned by @Jumhyn) I became curious about the answer to this question:
It seems to me that the rules that are statically enforced on noncopyable types could be leveraged (in some cases) to guarantee memory-safety without needing to subject one’s logic to the unpredictability of concurrency that is being discussed here.
I personally don't see much value in unique identities of values of non-copyable types. I don't think that creating an
ObjectIdentifier for them would work even if it made sense. Exclusive ownership on the other hand is much more important and it's something that developers have to deal with on daily basis. Unique identity may be a corollary of exclusive ownership, but it looks to me like a curious side effect and not something anyone would have to deal with.