[cfe-dev] Even more clang ideas

Ted Kremenek kremenek at apple.com
Sat Jul 26 10:31:07 PDT 2008

On Jul 26, 2008, at 1:17 AM, Ken Ferry wrote:

> 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];

This limitation also exists in Java with its own collection classes  
(collections use type erasure).  Lists, Maps, etc., all contain  
objects that subclass Object (the root of the Object hierarchy).   
Clients must use downcasts when retrieving objects from collections.   
Generics in Java helps reduce the typing for this, but its just  
syntactic sugar (the compiler inserts the downcast checks):


> 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".

I agree that this kind of polymorphism would be nice to have in  
Objective-C.  In many cases this kind of polymorphism can be  
implemented in C++ using templates.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20080726/70aa9c33/attachment.html>

More information about the cfe-dev mailing list