[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Questions on the return statement
From: |
Gary Polhill |
Subject: |
Re: Questions on the return statement |
Date: |
Thu, 04 Mar 1999 09:50:15 +0000 |
Fabio Mascelloni wrote:
>
> Suppose I declare such an instance variable :
>
> unsigned *inst;
>
> Then I initialize it to some value:
>
> - intitInstVar:(unsigned) length
> {
> inst=calloc ( length, sizeof (unsigned));
> //init in some way with some values
> return self;
> }
>
> After that I implement a method that could be invoked by objects of unrelated
> classes and that returns the instance variable:
>
> -(unsigned *) getInstVar
> {
> return inst;
> }
>
> The question is: does getInstVar returns a copy of the object or simply a
> reference to it ?
> If it simply returns a reference, how can I make it return a copy of the
> object ?
something like
-(unsigned *)getInstVar {
int i;
unsigned *copyOfInst;
copyOfInst = calloc(instVarLength, sizeof(unsigned));
// instVarLength should be set to length in initInstVar:
for(i = 0; i < instVarLength; i++)
copyOfInst[i] = inst[i];
return copyOfInst;
}
This is a good way to leak memory, however. It would be better to create and
allocate memory for the copy in the calling method -- that way it's easier to
look for variables that have been given memory and not freed. getInstVar would
then be something like:
-(unsigned *)getInstVar: (unsigned *)copyOfInst {
int i;
for(i = 0; i < instVarLength; i++)
copyOfInst[i] = inst[i];
return copyOfInst;
}
> In J.J Merelo's Breeder there's a method to get the genotype of a chromosome:
>
> - getGenotype
> {
> return (id) genotype;
> }
> where genotype is defined as unsigned char *genotype.Is this the right way?
No, my understanding of Obj-C is a little vague, but as far as I know id
is still a pointer type (even though there's no *), i.e. getGenotype still
returns a reference to, rather than a copy of genotype. The reference has
merely been cast to type id rather than type unsigned char *.
Gary
--
Macaulay Land Use Research Institute, Craigiebuckler, Aberdeen. AB15 8QH
Tel: +44 (0) 1224 318611 Email: address@hidden
==================================
Swarm-Support is for discussion of the technical details of the day
to day usage of Swarm. For list administration needs (esp.
[un]subscribing), please send a message to <address@hidden>
with "help" in the body of the message.