Re: red black trees
Re: red black trees
- Subject: Re: red black trees
- From: Glen Low <email@hidden>
- Date: Thu, 26 Feb 2004 06:37:21 +0800
Jim:
On Feb 25, 2004, at 7:18 AM, Glen Low wrote:
C++ has good RAII technique
What's RAII?
Allan has ably explained this, but I just wanted to summarize.
In C++ an object destructor is automatically called when the object
goes out of scope (scope of variables is well defined in C, C++ and
ObjC). So e.g.
for (int i = 0; i < 100; ++i)
{
object a (12); // construct an object
...
// at this point, the object goes out of scope, so the destructor of
object is called.
}
This leads to a technique called "Resource Acquisition is
Initialization", where you write the constructor to "acquire" some
resource e.g. a file, a mutex, a ObjC pointer retain, and you write the
destructor to "release" the same resource.
What does that gain you?
At least 2 things:
1. You don't have to remember to explicitly acquire and release the
resource in your direct code. If you had a RAII wrapper for ObjC
pointers (Allan's CocoaSTL) or CFTypes (my macstl), you don't have to
write [x retain] and [x release] in your code. The release bit is
particularly important, because it relieves you from book-keeping
activities, as long as the function ends or the loop ends, the release
will then happen automatically.
2. If your code throws exceptions or has a return in the middle of a
function or loop, the destructor and thus resource release is still
called. This avoids the coding style where if you have an error in the
middle of some processing, you as the programmer have to figure out
what has been acquired and release only that e.g.
NSObject* a;
NSObject* b;
NSObject* c;
a = ....
....
b = ....
if (err)
{
// have to make sure that all alloc'ed object so far are released
// hmm.. have I alloc'ed c yet?
[b release];
[a release];
return;
}
c = ....
if (err)
{
[c release];
[b release];
[a release];
return;
}
....
becomes:
object a, b, c;
a (...);
...
b (...);
if (err)
return; // automatically calls destructor on a, b, and releases
resources
c (...);
if (err)
return; // ditto and for c as well
....
Cheers, Glen Low
---
pixelglow software | simply brilliant stuff
www.pixelglow.com
_______________________________________________
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.