Re: copying immutable objects
Re: copying immutable objects
- Subject: Re: copying immutable objects
- From: Ondra Cada <email@hidden>
- Date: Fri, 17 May 2002 04:13:27 +0200
On Friday, May 17, 2002, at 02:50 , Robert Goldsmith wrote:
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.
Is that a typo? Any object in pool gets *released* when the pool is
released. Autoreleasing just places an object into the active pool -- it
does not touch the retain count.
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.
This seems somewhat confusing, but right you are. For immutable objects,
copy is usually implemented the simplest way:
-copy { return [self retain]; }
Therefore, you are speaking of *one* object only.
I assume this is because, for immutable objects, only a pointer to the
same object is created, not a real copy.
Well, right, thought I would not use exactly these words ("pointer is
created" looks to me obfuscating, though I do agree it is just plain truth
after all).
This all seems a little to easy to get wrong and could cause all sorts of
bugs.
None of that. Why? It's actually simple and quite non-bug-prone:
- if you did "copy", the result is yours to be used till you send it
"(auto)release";
- after that, you can't use it, lest your program crashes.
For immutable objects, there is no difference from this POV between "copy"
and "retain", and therefore internally "retain" is used...
1) Why is it done this way? (I assume efficiency)
...for efficiency, right.
2) Is there a different way that will force the two objects to behave
themselves! (at least as far as reference counting is concerned)
Sorry, but I don't undertstand the question? What do you mean by "two
objects behave themselves"?
---
Ondra Cada
OCSoftware: email@hidden
http://www.ocs.cz
2K Development: email@hidden
http://www.2kdevelopment.cz
private email@hidden
http://www.ocs.cz/oc
_______________________________________________
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.