Re: red black trees
Re: red black trees
- Subject: Re: red black trees
- From: Allan Odgaard <email@hidden>
- Date: Wed, 25 Feb 2004 18:07:19 +0100
On 25. Feb 2004, at 17:26, Jim Rankin wrote:
C++ has good RAII technique
What's RAII?
Resource Acquisition Is Initialization. Best explained by example.
For example we can define a class like this (in our library):
struct atsu_style
{
atsu_style () { status = ATSUCreateStyle(&style); }
~atsu_style () { if(status == noErr)
ATSUDisposeStyle(style); }
operator bool () { return status == noErr; }
operator ATSUStyle () { return style; }
private:
OSStatus status;
ATSUStyle style;
};
Now in user code all we write is this:
1 void render_text ()
2 {
3 atsu_style style;
4 if(style)
5 {
6 ATSUSetAttributes(style, ...);
7 ...
8 }
9 }
Line 3 will call the constructor of atsu_style which create the style.
Line 4 will use 'operator bool', which return true if the style was
allocated
Line 5 will use 'operator ATSUStyle' to "convert" the object to the
type required by ATSUSetAttributes().
In line 8 we leave the scope, and since 'style' has automatic storage
(stack) it will be destroyed, and thus the destructor is called which
in turn call ATSUDisposeStyle().
So basically you move the setup/cleanup code from your user code to
some shared class which deals with it.
I have written a class similar to the above for handling Mac OS
resources (it is templated on the type of resource and a function to
destroy the resource).
It has an advantage over the above, namely that it also supports
copying, so in the above the style is always destroyed when we leave
the scope, but we can implement operator= and copy construction so that
ownership of the resource is shared amongst copies of the class, and
first when the last copy is destroyed, will we dispose the resource.
That allows code like:
atsu_style bold_style (NSFont* font)
{
atsu_style s;
...
return s;
}
void render ()
{
map<string, atsu_style> m;
m["bold"] = bold_style();
m["italic"] = italic_style();
...
draw_text_with_styles(text, m);
}
In this code the styles are created in the make functions, but because
they are returned (by copy) they will not be disposed when leaving the
function scope -- instead they will be destroyed when the map is
destroyed (because the map contain a copy of the styles, preventing the
resource from being disposed), which is when the map goes out of scope
(i.e. when leaving the render function).
_______________________________________________
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.