develooper Front page | perl.perl6.language | Postings from March 2005

Re: return of copies vs references

Thread Previous | Thread Next
From:
Piers Cawley
Date:
March 28, 2005 22:10
Subject:
Re: return of copies vs references
Message ID:
m2u0mvx9rl.fsf@obelisk.bofh.org.uk
Darren Duncan <darren@DarrenDuncan.net> writes:

> At 11:26 PM -0700 3/16/05, Luke Palmer wrote:
>>  > For each of the above cases, is a copy of or a reference to the
>>>  attribute returned?  For each, will the calling code be able to
>>>  modify $obj's attributes by modifying the return values, or not?
>>
>>Well if you're making accessors, why the heck are you making them
>>private?  But I can't really answer your question, because it depends on
>>how you write the accessors.
>
> I am writing accessors to mediate with the attributes, which are all private,
> and whose implementation may change over time.  What I want, in the normal
> case, is that calling code which invokes my methods will get a copy of
> attributes which it can modify, that won't affect the original attribute
> values.
>
> When I last asked a related question here, I was told that simply returning
> an attribute will allow the caller to modify the original attribute by
> default.  I wanted to make sure this didn't happen.  It is possible that
> there was a misunderstanding regarding the previous question, and the default
> action is in fact a copy.

Doesn't that rather depend on the type of the attribute? Personally, if I get
an object back from accessor method then I expect that any modifications of
that object's state will be seen the next time I look at the results of that
accessor method. This is a direct result of the way reference types work, and
the world is a better place because of it. If you want a (deep) copy of the
returned object you should say so:

   my $res = $object.attribute.clone;



    

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About