Re: copying immutable objects
Re: copying immutable objects
- Subject: Re: copying immutable objects
- From: Nathan Day <email@hidden>
- Date: Fri, 17 May 2002 21:53:27 +0930
On Friday, May 17, 2002, at 10:20 AM, Robert Goldsmith wrote:
Sorry to all you people out there wanting to cover real issues but
there is one question about copying immutable objects that has been
bugging me:
If you create an object so that it is added to the autorelease pool
implicitly by creating it using a factory method, it has a retain count
of 1 and gets autoreleased when the pool is released.
If you take a copy of that object, both the new and the old copy of the
object get their retain count increased but the second object is not
added to the autorelease pool so, when the first object is released,
actually, both still exist but, obviously, releasing both of them will
cause an error, as will accessing one after releasing the other.
I assume this is because, for immutable objects, only a pointer to the
same object is created, not a real copy.
This all seems a little to easy to get wrong and could cause all sorts
of bugs.
Therefore:
1) Why is it done this way? (I assume efficiency)
2) Is there a different way that will force the two objects to behave
themselves! (at least as far as reference counting is concerned)
Since an immutable object can't be changed it doesn't make sense to make
a copy of it, just increase the retain count. The autorelease pool
doesn't deallocate objects it just releases them. Releasing an object
decrease an objects retain count by one, if the retain count reaches
zero then every retain (++1) has been matched with a release (--1)
therefore nobody must want the object anymore, so the object is then
deallocated. The retain count represents how many (places/times
whatever) the object is needed.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.