[cfe-dev] Even more clang ideas

Ken Ferry kenferry at gmail.com
Sat Jul 26 01:17:33 PDT 2008

On Sat, Jul 26, 2008 at 12:02 AM, Chris Hanson <cmh at me.com> wrote:
> On Jul 25, 2008, at 6:28 PM, Ted Kremenek wrote:
>>> It is, in fact, an error to return a NSMutableArray in a method
>>> that's prototyped to return an NSArray due to C pointer aliasing
>>> rules. The 'id' type is the closest thing that Objective-C has to a
>>> 'generic object pointer type', so if a method wants to return a
>>> pointer to an object of more than one type, it really should declare
>>> the return type as 'id'.
> John is also incorrect about the above:  It is *not* an error, in
> Objective-C, to return an instance of a subclass from a method
> prototyped as returning an instance of the superclass.

John may be thinking of the fact that most init methods and such
return id, for example -[NSArray initWithObjects:].  This isn't
because it would be incorrect to return (NSArray *), it's because
subclassers would have to redeclare every init method, or else the
compiler would issue a warning for lines such as

NSMutableArray *mutableArray = [[NSMutableArray alloc]
initWithObjects:obj1, obj2, nil];

Actually, since the +alloc method returns id (for the same reason),
the compiler cannot even tell that -[NSMutableArray initWithObjects:]
should be preferred over -[NSArray initWithObjects:] here.

It'd be nice if Objective-C had return types that meant "instance of
receiver" and "instance of receiver's class".


More information about the cfe-dev mailing list