[swift-dev] COW for non-mutating methods

Patrick Pijnappel patrickpijnappel at gmail.com
Thu Dec 1 05:29:09 CST 2016


I'm implementing a COW big int type but am running into problems with
non-mutating functions (e.g. the + operator). Simplified example code below
shows AFAIK the default way to implement COW, but the non-mutating method
doesn't identify the reference as unique (even with -O), resulting in a
needless copy.

I've tried everything I could think of, but only inout parameters seem to
work. How does the standard library do this, for e.g. String + String?


struct Foo {

  var storage = Storage()


  class Storage { var x = 0 }


  init(_ x: Int) { storage.x = x }


  mutating func negate() {

    if !isKnownUniquelyReferenced(&storage) {

      print("Copy")

    }

    storage.x = -storage.x

  }


  func negated() -> Foo {

    var result = self // This counts as a second reference

    result.negate()

    return result

  }

}


func test() {

  var a = Foo(5)

  a.negate()

  print(a.storage.x)


  let b = Foo(5)

  let c = b.negated()

  print(c.storage.x)

}


test()



*Output*

-5

Copy

-5
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20161201/fd0f1b27/attachment.html>


More information about the swift-dev mailing list