> On Mar 31, 2016, at 4:21 PM, Joe Groff via swift-dev <swift-dev@swift.org> > wrote: > >> >> On Mar 31, 2016, at 3:58 PM, Patrick Pijnappel via swift-dev >> <swift-dev@swift.org> wrote: >> >> In trying to implement a COW type, but I'm running into problems with >> isUniqueReferenced breaking in even fairly simple cases. For example (with >> -O) the code below prints "bar: false", commenting out the print in test() >> makes it print "bar: true", and removing the var parameter var foo: Foo and >> using var foo = foo instead breaks it again. Am I doing something wrong here? >> >> class FooStorage { var x: Int = 0 } >> >> struct Foo { var storage = FooStorage() } >> >> func bar(var foo: Foo) { >> print("bar: \(isUniquelyReferencedNonObjC(&foo.storage))") >> } >> >> func test() { >> var foo = Foo() >> print("test: \(isUniquelyReferencedNonObjC(&foo.storage))") >> bar(foo) >> } >> >> test() > > You're not doing anything wrong, this is just the ARC optimizer at work. > `foo` inside `test` is dead after the call to `bar`, so ownership is > transferred directly to `bar`'s parameter.
If you want to ensure that `foo` remains alive despite this, you can use `withExtendedLifetime`: class FooStorage { var x: Int = 0 } struct Foo { var storage = FooStorage() } func bar(var foo: Foo) { print("bar: \(isUniquelyReferencedNonObjC(&foo.storage))") } func test() { var foo = Foo() print("test: \(isUniquelyReferencedNonObjC(&foo.storage))") withExtendedLifetime(foo) { bar(foo) } } -Joe _______________________________________________ swift-dev mailing list swift-dev@swift.org https://lists.swift.org/mailman/listinfo/swift-dev