Basic Swift ownership-y questions

A holistic bag of internally contradictory design rationales:

  • Rule-of-3/5 programming is :japanese_ogre: :japanese_goblin:

    • We managed to avoid it by not having copy constructors/assignment operators
    • C++ interop is probably going to mean that we get it eventually, in some form :frowning_face:
    • I very much hope the vast majority of Swift programmers never have to deal with it
  • Swift today has a very nice property that storing a copy of any type is O(1)

    • Languages with copy constructors with O(N) copy operations, which lead to
    • …people trying to pass things by unsafe pointer to avoid copying cost, which means
    • …bypassing Swift's strict value semantics.
    • But maybe we can discourage the creation and use of such types and because of the CoW precedent, the effect of having copy constructors might not be so bad.
  • If it weren't for C++ interop:

    • I'd disallow structs to have copy constructors or assignment operators
    • I'd disallow copyable structs to have deinit
    • In this world, only move-only and “pinned” structs would have deinit.
    • The language would remain simple
    • Copies would always be O(1)
    • I can't think of many types useful to a Swift programmer that would be ruled out in such a world.
    • Implementing your own reference-counted owner is the one exception
    • Even that seems very much like a niche application that doesn't warrant complicating the language for.

All that said, since I'm working on C++ interop and ownership, I'm having a hard time avoiding the idea that we'll get something very much like full rule-of-5 member support for structs in Swift, eventually. It just needs to be designed and implemented. I hope to design it in such a way that it intrudes on the language as little as possible.

One thing I'm currently mulling over is the idea of importing all nontrivial C++ types as move-only structs in Swift, and providing only explicit __cxx_copy and __cxx_assign operations (spelling to be determined). It's not as crazy as you might think, since pass-by-value can use guaranteed calling convention. This might allow us to stay out of the rule-of-5 business.

5 Likes