[swift-dev] @owned vs @guaranteed convention for 'self' in nonmutating value type methods

John McCall rjmccall at apple.com
Tue Jan 19 12:29:57 CST 2016

> On Jan 19, 2016, at 10:05 AM, Joe Groff <jgroff at apple.com> wrote:
>> On Jan 19, 2016, at 9:53 AM, John McCall <rjmccall at apple.com> wrote:
>>> On Jan 18, 2016, at 9:28 AM, Joe Groff via swift-dev <swift-dev at swift.org> wrote:
>>> For Swift 2, we changed the default reference counting convention for 'self' parameters from +1 "owned" (caller retains, callee releases) to +0 "guaranteed" (caller retains and releases). This makes a lot of sense for class methods, since it's common to invoke a number of methods on the same object in turn. Similarly for value types, it's common to want to perform a bunch of mutations in a row, but we get a "+0"-like convention naturally due to the way 'inout' works. For nonmutating value type operations, it's a bit less clear-cut—a pure operation is more likely to appear once as part of a larger expression. Using +0 also prevents us from reusing self's resources and doing in-place mutation if it's uniquely referenced, which is an extremely useful optimization for a number of operations on strings and containers. We may want to consider whether +1 is a better default, if not for all nonmutating value type methods, maybe some subset where inplace mutation is likely to be profitable. One possible heuristic would be to look at whether a method returns the Self type (possibly including tuples and fragile structs containing Self, or different instantiations of the same Self type).
>> I feel like the right language solution here is probably just to add attributes to allow methods to opt-in to a different default self convention.
> We could do that, but we should still make sure the defaults give the best overall system performance and optimization opportunity.

Sure, but we’re talking about very narrow heuristics for changing the defaults here.  At most, maybe your Self rule, although there are conspicuous cases (func clone() -> Self) where it would not be appropriate.


More information about the swift-dev mailing list