[Pitch] Borrowing Accessors

Would it make sense to make borrowing the default? Accessors returning non copyable types already require borrowing. The difference would be that accessors returning non copyable types would use borrowing by default. Then, to retain current semantics, the compiler would insert a copy if needed. Essentially, we’d change when the copying occurs: instead of happening inside the accessor code, it would occur at the call site (if required).

The main benefit of this approach is that it lessens the divide between copyable and non-copyable types. That’s because “copying get” would remain the default choice for copyable types, but then non-copyable types would have to use the new “borrowing” modifier. In my opinion, there isn’t a big enough semantic difference to justify this syntactic difference this proposal creates. Granted, it’s mostly advanced programmers who will write their own efficient non-copyable types. Regardless, the confusion remains for the users of said efficient API who might not be as advanced.

The biggest issue I foresee with implicit borrows is that ABI-compatible libraries would need to generate copying get thunks. This brings me to my final point: performance.

My naive guess is that code across optimization boundaries (e.g. a dynamic library and its client) might slightly benefit from eliminating a copy where a borrow would suffice. On the other hand, generating thunks for dynamic libraries might add to code size. Also, if the accessor body already generates an owned value, exposing that as a borrow, and then copying again at the call site actually results in an extra copy. Ultimately, whether implicit borrows generally eliminate or add copies depends on if most accessors expose a property owned by the underlying type (borrow eliminates a copy) or compute/create the return value when called (borrow adds a copy).

To be clear, I think “copying get” should still be allowed; just not remain the default. Please let me know if this makes sense or was already discussed!

Best, Filip