[swift-dev] isUniquelyReferenced issues

Joe Groff jgroff at apple.com
Thu Mar 31 18:27:28 CDT 2016


> On Mar 31, 2016, at 4:21 PM, Joe Groff via swift-dev <swift-dev at swift.org> wrote:
> 
>> 
>> On Mar 31, 2016, at 3:58 PM, Patrick Pijnappel via swift-dev <swift-dev at 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


More information about the swift-dev mailing list