[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Automatic Reference Counting
From: |
David Chisnall |
Subject: |
Automatic Reference Counting |
Date: |
Wed, 29 Jun 2011 14:36:47 +0100 |
Hi Everyone,
This year I got a birthday present from Apple's compiler team: the open source
release of the compiler part of their automatic reference counting (ARC)
implementation. I've just finished adding the relevant support code to the
GNUstep runtime and to GNUstep Base.
If you're on the OS X or iOS developer programme (I'm not), then you've
probably already played with ARC. If you're not, then here's a quick overview:
Object pointers are now either __strong (the default), __weak, or
__unsafe_unretained. A __strong pointer contains an owning reference, meaning
that it accounts for one retain on the object. A __weak reference does not
contain an owning reference and will be automatically zero'd when the object
begins deallocation. An __unsafe_unretained pointer is not tracked by ARC at
all.
ARC does some quite nice things for you. For every assignment, the compiler
will automatically insert calls to runtime functions that do the retain /
release juggling for you. It will also implicitly add code to your objects
freeing all instance variables. Because of this, some things are not allowed
in ARC mode:
- Implementing -retain, -release, or -autorelease
- Calling -retain, -release, or -autorelease
- Storing object pointers that are not __unsafe_unretained qualified in
structures.
ARC code can be mixed with non-ARC code without any problems. This means that
you can compile GNUstep with manual reference counting, link against frameworks
that use manual reference counting,
and still use ARC in your own code.
Note that, unlike GC mode, __weak pointers are allowed on the stack in ARC
mode. You can, for example, do this:
Foo *f = [Foo new];
__weak id weak = f;
f = nil;
fprintf(stderr, "Weak: %p\n", weak);
This will always print Weak: 0 when you run it. ARC, like manual reference
counting, is deterministic. This code compiles to the equivalent of:
Foo *f = [Foo new]; // No retain, because +new returns an owning
reference
id weak;
objc_initWeak(&weak, f); // Register weak as a weak pointer, stores f
in it
objc_release(f); // Release f
f = nil;
objc_destroyWeak(&weak);
Apple has also open sourced the optimiser component, which will remove
redundant retain/release pairs and attempt to combine various calls into single
aggregate ones.
ARC is now the default mode for OS X and iOS development, so expect to see a
lot of code that uses it...
David
P.S. Apple's implementation of ARC is not available to the general public until
10.7 is released next month, so this means that GNUstep is shipping the first
publicly available (if not officially released) implementation of ARC.
-- Sent from my Difference Engine
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- Automatic Reference Counting,
David Chisnall <=