Re: Memory leak if alloc succeeds but init fails?
Re: Memory leak if alloc succeeds but init fails?
- Subject: Re: Memory leak if alloc succeeds but init fails?
- From: Wincent Colaiuta <email@hidden>
- Date: Fri, 28 Sep 2007 15:38:11 +0200
El 28/9/2007, a las 8:29, Half Activist escribió:
On a syntactic point of view, 'nil' can be seen as a fully
functional object, it can be distinguished from other instances
easily.
I suppose they meant that if the program wouldn't be able to tell a
fully functional instance of a class from a non functional one,
that is
what the initialization returns cannot be interpreted as a failure
or a success from its result, then the initialization methods
must raise an exception to tell that something wrong happened.
Still, this would be really weird to proceed this way in an init
method. :-\
Exceptions should really only be used to signal programmer errors;
that is failed assumptions (things you assume to be true).
So I would say, return nil if the failure to initialize is caused by
an external factor outside of your control, and raise an exception if
your assumptions about what state should be true have not been met.
As an obvious example, in the init method you *assume* that the
programmer will pass the correct parameters according to the
specifications that you make in the docs. This is an assumption, and
an assumption is an expectation that you should test in order to
catch programmer errors. You test this expectation and throw an
exception if it is not met (ie. you use NSParameterAssert which
throws an NSInternalInconsistencyException). But if there is
something outside of your control (eg. you need to read a file but
you find that you don't have access permission) you release yourself
and return nil.
Given that you raise exceptions only to indicate programmer errors,
the little bit of leaked memory in the exception case is the last
thing you need to worry about. You *could* release before throwing if
you want, but why fix a leak in a code path that you expect to never
take? Better to catch and fix programmer errors as soon as you find
them.
Not sure if I've described that very clearly, but hopefully you get
the idea.
Cheers,
Wincent
_______________________________________________
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