Re: Memory Allocation
Re: Memory Allocation
- Subject: Re: Memory Allocation
- From: "Michael Ash" <email@hidden>
- Date: Wed, 16 Jul 2008 17:19:41 -0400
On Wed, Jul 16, 2008 at 2:38 PM, Kyle Sluder
<email@hidden> wrote:
> On Wed, Jul 16, 2008 at 2:02 PM, Alexandre Badez
> <email@hidden> wrote:
>> -(id)init
>> {
>> if (![super init])
>> return nil;
>
> You must always assign self to the result of [super init]. If anyone
> (*cough* Wil Shipley *cough*) tells you otherwise, they may
> inadvertently set you up for some seriously subtle errors.
Can you explain this, in particular how the "standard" initializer
sets you up for fewer seriously subtle errors than this one?
It seems to me that the possible return values from the [super init]
call can be broken into three categories:
A) self
B) nil
C) Something Else
A is obviously the common case, and B is the standard way to signal a
failure. Both the standard initializer and this one handle A and B
just fine, so they aren't all that interesting. That leaves us with C.
In the case of C, this initializer crashes and burns. If [super init]
returns another object, then it will free self, and then you'll be
accessing self after it's freed. Obviously this is bad.
However, the standard initializer *also* crashes and burns in the case
of C. The Something Else could be anything. It may not even be an
instance of your class, in which case you're accessing ivars that
aren't there, and you'll fail horribly.If it is an instance of your
class then it's virtually guaranteed to already be initialized, in
which case you're initializing twice, which could lead to anything
from a memory leak to a crash to data corruption.
If I've overlooked anything, I'd appreciate hearing about it. I do use
the standard if((self = [super init])) technique, but just out of
habit and conformity, as I have not been able to detect any actual
benefit from it.
Mike
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden