Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
09/12/11 6:41 PM
__autoreleasing
objects
Page 1 of 32
09/12/11 6:41 PM
7. Miscellaneous
7.1. Special methods
7.1.1. Memory management methods
7.1.2.
dealloc
7.2.
@autoreleasepool
7.3.
self
value);
8.2.
8.3.
void *objc_autoreleasePoolPush(void);
8.4.
id objc_autoreleaseReturnValue(id value);
8.5.
8.6.
8.7.
8.8.
id objc_loadWeak(id *object);
8.9.
id objc_loadWeakRetained(id *object);
8.10.
8.11.
8.12.
id objc_retain(id value);
8.13.
id objc_retainAutorelease(id value);
8.14.
id objc_retainAutoreleaseReturnValue(id value);
8.15.
id objc_retainAutoreleasedReturnValue(id value);
8.16.
id objc_retainBlock(id value);
8.17.
8.18.
Page 2 of 32
09/12/11 6:41 PM
The secondary purpose is to act as a rationale for why ARC was designed
in this way. This should remain tightly focused on the technical design
and should not stray into marketing speculation.
1.2. Background
This document assumes a basic familiarity with C.
This looks in the dynamic class of the receiver for a method with this
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 3 of 32
09/12/11 6:41 PM
This looks in the dynamic class of the receiver for a method with this
name, then in that class's superclass, etc., until it finds something it can
execute. The receiver "expression" may also be the name of a class, in
which case the actual receiver is the class object for that class, or (within
method definitions) it may be super, in which case the lookup algorithm
starts with the static superclass instead of the dynamic class. The actual
methods dynamically found in a class are not those declared in the
@interface, but those defined in a separate @implementation declaration;
however, when compiling a call, typechecking is done based on the
methods declared in the @interface.
Method declarations may also be grouped into protocols, which are not
inherently associated with any class, but which classes may claim to
follow. Object pointer types may be qualified with additional protocols
that the object is known to support.
2. General
Automatic Reference Counting implements automatic memory
management for Objective-C objects and blocks, freeing the programmer
from the need explicitly insert retains and releases. It does not provide a
cycle collector; users must explicitly manage lifetime instead.
ARC may be explicitly enabled with the compiler flag -fobjc-arc. It may
also be explicitly disabled with the compiler flag -fno-objc-arc. The last of
these two flags appearing on the compile line "wins".
If ARC is enabled,
__has_feature(objc_arc)
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
09/12/11 6:41 PM
Class, NSFoo*,
etc.)
__attribute__((NSObject))
int*
and
CFStringRef,
__attribute__((NSObject))
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
09/12/11 6:41 PM
absolutely necessary to use this attribute, be very explicit about using the
typedef, and do not assume that it will be preserved by language features
like __typeof and C++ template argument substitution.
release,
autorelease,
void.
Page 6 of 32
09/12/11 6:41 PM
This attribute is part of the type of the function or method, not the type of
the parameter. It controls only how the argument is passed and received.
When passing such an argument, ARC retains the argument prior to
making the call.
When receiving such an argument, ARC releases the argument at the end
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 7 of 32
09/12/11 6:41 PM
When receiving such an argument, ARC releases the argument at the end
of the function, subject to the usual optimizations for local values.
Page 8 of 32
09/12/11 6:41 PM
caller. The most common scenario this models is the retained return from
init, alloc, new, and copy methods, but there are other cases in the
frameworks. After optimization there are typically no extra retains and
releases required.
Methods in the alloc, copy, init, mutableCopy, and new families are implicitly
marked __attribute__((ns_returns_retained)). This may be suppressed by
explicitly marking the method __attribute__((ns_returns_not_retained)).
It is undefined behavior if the method to which an Objective-C message
send statically resolves has different retain semantics on its result from
the method it dynamically resolves to. It is undefined behavior if a block
or function call is made through a static type with different retain
semantics on its result from the implementation of the called block or
function.
Page 9 of 32
09/12/11 6:41 PM
casts the operand, which must have nonretainable pointer type, to the destination type, which must be a
retainable object pointer type. ARC will release the value at the end of
the enclosing full-expression, subject to the usual optimizations on
local values.
(__bridge_transfer T) op
These casts are required in order to transfer objects in and out of ARC
control; see the rationale in the section on conversion of retainable object
pointers.
Using a __bridge_retained or __bridge_transfer cast purely to convince ARC
to emit an unbalanced retain or release, respectively, is poor form.
3.3. Restrictions
3.3.1. Conversion of retainable object pointers
In general, a program which attempts to implicitly or explicitly convert a
value of retainable object pointer type to any non-retainable type, or viceversa, is ill-formed. For example, an Objective-C object pointer shall not
be converted to void*. As an exception, cast to intptr_t is allowed because
such casts are not transferring ownership. The bridged casts may be used
to perform these conversions where necessary.
cf_returns_retained
cf_returns_not_retained
attribute and
ns_returns_retained
Page 10 of 32
09/12/11 6:41 PM
__bridge
cast.
4. Ownership qualification
This section describes the behavior of objects of retainable object pointer
type; that is, locations in memory which store retainable object pointers.
A type is a retainable object owner type if it is a retainable object
pointer type or an array type whose element type is a retainable object
owner type.
An ownership qualifier is a type qualifier which applies only to retainable
object owner types. An array type is ownership-qualified according to its
element type, and adding an ownership qualifier to an array type so
qualifies its element type.
A program is ill-formed if it attempts to apply an ownership qualifier to a
type which is already ownership-qualified, even if it is the same qualifier.
There is a single exception to this rule: an ownership qualifier may be
applied to a substituted template type parameter, which overrides the
ownership qualifier provided by the template argument.
Except as described under the inference rules, a program is ill-formed if it
attempts to form a pointer or reference type to a retainable object owner
type which lacks an ownership qualifier.
Rationale: these rules, together with the inference rules, ensure that all
objects and lvalues of retainable object pointer type have an ownership
qualifier. The ability to override an ownership qualifier during template
substitution is required to counteract the inference of __strong for
template type arguments.
There are four ownership qualifiers:
__autoreleasing
__strong
__unsafe_unretained
__weak
4.1. Spelling
The names of the ownership qualifiers are reserved for the
implementation. A program may not assume that they are or are not
implemented with macros, or what those macros expand to.
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 11 of 32
09/12/11 6:41 PM
implies
__unsafe_unretained
ownership.
retain
implies
__strong
ownership.
strong
implies
__strong
ownership.
unsafe_unretained
weak
implies
implies
__weak
__unsafe_unretained
ownership.
ownership.
weak,
4.2. Semantics
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 12 of 32
09/12/11 6:41 PM
4.2. Semantics
There are five managed operations which may be performed on an object
of retainable object pointer type. Each qualifier specifies different
semantics for each of these operations. It is still undefined behavior to
access an object outside of its lifetime.
A load or store with "primitive semantics" has the same semantics as the
respective operation would have on an void* lvalue with the same
alignment and non-ownership qualification.
Page 13 of 32
09/12/11 6:41 PM
4.3. Restrictions
4.3.1. Weak-unavailable types
It is explicitly permitted for Objective-C classes to not support __weak
references. It is undefined behavior to perform an operation with weak
assignment semantics with a pointer to an Objective-C object whose class
does not support __weak references.
Rationale: historically, it has been possible for a class to provide its own
reference-count implementation by overriding retain, release, etc.
However, weak references to an object require coordination with its class's
reference-count implementation because, among other things, weak loads
and stores must be atomic with respect to the final release. Therefore,
existing custom reference-count implementations will generally not
support weak references without additional effort. This is unavoidable
without breaking binary compatibility.
A class may indicate that it does not support weak references by providing
the objc_arc_weak_unavailable attribute on the class's interface declaration.
A retainable object pointer type is weak-unavailable if is a pointer to an
(optionally protocol-qualified) Objective-C class T where T or one of its
superclasses has the objc_arc_weak_unavailable attribute. A program is illformed if it applies the __weak ownership qualifier to a weak-unavailable
type or if the value operand of a weak assignment operation has a weakunavailable type.
__autoreleasing
object of non-
Rationale: autorelease pools are tied to the current thread and scope by
their nature. While it is possible to have temporary objects whose instance
variables are filled with autoreleased objects, there is no way that ARC can
provide any sort of safety guarantee there.
It is undefined behavior if a non-null pointer is assigned to an
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 14 of 32
09/12/11 6:41 PM
cv
reinterpret_cast
in Objective-C++;
T&
and
U&
in Objective-C++.
Page 15 of 32
09/12/11 6:41 PM
is
__strong
or
__weak,
and
T __strong *
with a
U __strong *.
of type
U oq *.
T __autoreleasing
is created and
Page 16 of 32
09/12/11 6:41 PM
actual call.
6. After the call completes, the temporary is loaded with primitive
semantics, and that value is assigned into *p.
Rationale: the resulting type would be non-POD in the C++ sense, but C
does not give us very good language tools for managing the lifetime of
aggregates, so it is more convenient to simply forbid them. It is still
possible to manage this with a void* or an __unsafe_unretained object.
This restriction does not apply in Objective-C++. However, nontrivally
ownership-qualified types are considered non-POD: in C++11 terms, they
are not trivially default constructible, copy constructible, move
constructible, copy assignable, move assignable, or destructible. It is a
violation of C++ One Definition Rule to use a class outside of ARC that,
under ARC, would have an ownership-qualified member.
Rationale: unlike in C, we can express all the necessary ARC semantics for
ownership-qualified subobjects as suboperations of the (default) special
member functions for the class. These functions then become non-trivial.
This has the non-obvious repercussion that the class will have a nontrivial copy constructor and non-trivial destructor; if it wouldn't outside of
ARC, this means that objects of the type will be passed and returned in an
ABI-incompatible manner.
Page 17 of 32
09/12/11 6:41 PM
is
const-qualified
or
Class,
is an ownership-
__unsafe_unretained;
__autoreleasing.
Rationale: __autoreleasing exists mostly for this case, the Cocoa convention
for out-parameters. Since a pointer to const is obviously not an outparameter, we instead use a type more useful for passing arrays. If the
user instead intends to pass in a mutable array, inferring __autoreleasing is
the wrong thing to do; this directs some of the caution in the following
rules about writeback.
Such a type written anywhere else would be ill-formed by the general rule
requiring ownership qualifiers.
This rule does not apply in Objective-C++ if a parameter's type is
dependent in a template pattern and is only instantiated to a type which
would be a pointer to an unqualified retainable object pointer type. Such
code is still ill-formed.
5. Method families
An Objective-C method may fall into a method family, which is a
conventional set of behaviors ascribed to it by the Cocoa conventions.
A method is in a certain method family if:
it has a
that,
objc_method_family
objc_method_family
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 18 of 32
09/12/11 6:41 PM
mutableCopy
new
methods must be instance methods and must return an ObjectiveC pointer type. Additionally, a program is ill-formed if it declares or
contains a call to an init method whose return type is neither id nor a
pointer to a super-class or sub-class of the declaring class (if the
method was declared on a class) or the static receiver type of the call
(if it was declared on a protocol).
init
Page 19 of 32
09/12/11 6:41 PM
Page 20 of 32
09/12/11 6:41 PM
alloc
and
init
new
method families
family
self
retain
and
autorelease
Rationale: ARC's automatic code emission is more prone than most code
to signature errors, i.e. errors where a call was emitted against one
method signature, but the implementing method has an incompatible
signature. Having more precise type information helps drastically lower
this risks, as well as catching a number of latent bugs.
6. Optimization
ARC applies aggressive rules for the optimization of local behavior. These
rules are based around a core assumption of local balancing: that other
code will perform retains and releases as necessary (and only as
necessary) for its own safety, and so the optimizer does not need to
consider global properties of the retain and release sequence. For
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 21 of 32
09/12/11 6:41 PM
7. Miscellaneous
7.1. Special methods
7.1.1. Memory management methods
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 22 of 32
09/12/11 6:41 PM
7.1.2. dealloc
A program is ill-formed if it contains a message send or
expression for the selector dealloc.
dealloc
@selector
directly.
Page 23 of 32
09/12/11 6:42 PM
7.2. @autoreleasepool
To simplify the use of autorelease pools, and to bring them under the
control of the compiler, a new kind of statement is available in ObjectiveC. It is written @autoreleasepool followed by a compound-statement, i.e. by
a new scope delimited by curly braces. Upon entry to this block, the
current state of the autorelease pool is captured. When the block is exited
normally, whether by fallthrough or directed control flow (such as return
or break), the autorelease pool is restored to the saved state, releasing all
the objects in it. When the block is exited with an exception, the pool is
not drained.
@autoreleasepool
semantics.
A program is ill-formed if it refers to the
NSAutoreleasePool
class.
7.3. self
The self parameter variable of an Objective-C method is never actually
retained by the implementation. It is undefined behavior, or at least
dangerous, to cause an object to be deallocated during a message send to
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 24 of 32
09/12/11 6:42 PM
7.5. Blocks
The implicit const capture variables created when evaluating a block literal
expression have the same ownership semantics as the local variables they
capture. The capture is performed by reading from the captured variable
and initializing the capture variable with that value; the capture variable is
destroyed when the block literal is, i.e. at the end of the enclosing scope.
The inference rules apply equally to __block variables, which is a shift in
semantics from non-ARC, where __block variables did not implicitly retain
during capture.
variables of retainable object owner type are moved off the stack
by initializing the heap copy with the result of moving from the stack
copy.
__block
Page 25 of 32
09/12/11 6:42 PM
7.6. Exceptions
By default in Objective C, ARC is not exception-safe for normal releases:
It does not end the lifetime of __strong variables when their scopes are
abnormally terminated by an exception.
It does not perform releases which would occur at the end of a fullexpression if that full-expression throws an exception.
A program may be compiled with the option -fobjc-arc-exceptions in order
to enable these, or with the option -fno-objc-arc-exceptions to explicitly
disable them, with the last such argument "winning".
-fobjc-arc-exceptions
is enabled by default.
Page 26 of 32
09/12/11 6:42 PM
Rationale: not all memory and resources are managed with reference
counts; it is common for objects to manage private resources in their own,
private way. Typically these resources are completely encapsulated within
the object, but some classes offer their users direct access for efficiency.
If ARC is not aware of methods that return such "interior" pointers, its
optimizations can cause the owning object to be reclaimed too soon. This
attribute informs ARC that it must tread lightly.
The extension rules are somewhat intentionally vague. The autorelease
pool limit is there to permit a simple implementation to simply retain and
autorelease the receiver. The other limit permits some amount of
optimization. The phrase "derived from" is intended to encompass the
results both of pointer transformations, such as casts and arithmetic, and
of loading from such derived pointers; furthermore, it applies whether or
not such derivations are applied directly in the calling code or by other
utility code (for example, the C library routine strchr). However, the
implementation never need account for uses after a return from the code
which calls the method returning an interior pointer.
As an exception, no extension is required if the receiver is loaded directly
from a __strong object with precise lifetime semantics.
8. Runtime support
This section describes the interaction between the ARC runtime and the
code generated by the ARC compiler. This is not part of the ARC language
specification; instead, it is effectively a language-specific ABI supplement,
akin to the "Itanium" generic ABI for C++.
Ownership qualification does not alter the storage requirements for
objects, except that it is undefined behavior if a __weak object is
inadequately aligned for an object of type id. The other qualifiers may be
used on explicitly under-aligned memory.
The runtime tracks __weak objects which holds non-null values. It is
undefined behavior to direct modify a __weak object which is being tracked
by the runtime except through an objc_storeWeak, objc_destroyWeak, or
objc_moveWeak call.
The runtime must provide a number of new entrypoints which the
compiler may emit, which are described in the remainder of this section.
Page 27 of 32
09/12/11 6:42 PM
value
If value is null, this call has no effect. Otherwise, it adds the object to the
innermost autorelease pool exactly as if the object had been sent the
autorelease message.
Always returns
value.
value
If value is null, this call has no effect. Otherwise, it makes a best effort to
hand off ownership of a retain count on the object to a call to
objc_retainAutoreleasedReturnValue for the same object in an enclosing call
frame. If this is not possible, the object is autoreleased as above.
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 28 of 32
09/12/11 6:42 PM
Always returns
value.
objc_storeWeak
on
src.
objc_storeWeak
on
object
value
object
objc_storeWeak
on
Page 29 of 32
If
09/12/11 6:42 PM
object
is registered as a
__weak
id objc_loadWeak(id *object) {
return objc_autorelease(objc_loadWeakRetained(object));
}
objc_storeWeak
on
object.
objc_storeWeak
on
object.
objc_storeWeak
on
src.
value
value
value.
Page 30 of 32
09/12/11 6:42 PM
value
Always returns
value.
value
Always returns
value.
value
value.
value
__strong
object of non-
Page 31 of 32
09/12/11 6:42 PM
Always returns
value.
object
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.consumed
Page 32 of 32