|
|
Comments and Discussions
|
|
 |

|
Nice article.
Several years passed since this article was posted - just some heads-up to the readers who are unfamiliar with WTL - an originally MS extension to ATL.
WTL has many wrapper-like classes to standard window handles, such as HFONT, HDC, HBRUSH, HWND and many many more.
For example:
typedef CMenuT CMenuHandle;
typedef CMenuT CMenu;
typedef CPenT CPenHandle;
typedef CPenT CPen;
atlgdi.h:
// CPenT
// CBrushT
// CLogFont
// CFontT
// CBitmapT
// CPaletteT
// CRgnT
// CDCT
atluser.h:
// CMenuItemInfo
// CMenuT
// CAcceleratorT
// CIconT
// CCursorT
----
Cheers
/Zeev
|
|
|
|

|
operandx wrote: Several years passed since this article was posted
Scary, somehow.
I've said that before some posts below - my problem is that the "delete it or not" flag is a template parameter, meaning I can't assign a CMenuT<true> to a CMenuT<false> - so I can't decide about policy only when I create the handle. They work very well as "scope guards" - i.e. making sure some handle is destroyed when the wrapper leaves scope. I aimed at a bit more than that.
Anyway, thanks for your feedback
As mos feedback shows, this is only a partial and/or incomplete solution - this is also my experience using them.
|
|
|
|

|
The kernel has a reference count for handles (all handles) that you ask it to create. The problem is that many people don't pass handles correctly. If you are going to do anything that you think should require an increment to the reference count, you should use DuplicateHandle (and a subsequent call to the appropriate release method). Adding another reference count to it will just decrease the performance of your applications.
As an aside, MFC knows about the kernel reference counting and hence its wrappers handle them properly (in most cases).
If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week
Zac
|
|
|
|

|
Important point. Still, I'm not convinced
Zac Howland wrote: many people don't pass handles correctly
The problem I try to solve is not passing, but returning and storing.
I see the following advantagesof this solution:
(1) Not all "Handle-Like things" have an DuplicateHandle.
One example: Registry keys (not technically kernel handles, you can open another handle to the same key, but you lose the access rights of the original HKEY)
(2) The solution is generic for all pointer-sized handles. Less code, less test cases, less things to know. A custom implementation for fonts would be very expensive (HFONT -> LOGFONT -> HFONT, or is there a better one?)
(3) The kernel reference count isn't available (directly or indirectly) in user mode.
E.g. DuplicateHandle has two drawbacks:
It returns a new handle value (I tried XP SP2, file handle, DUPLICATE_SAME_ACCESS). So we can safely assume using DuplicateHandle takes longer and eats additional resources per copy.
Further, the copy operation could fail, which must be handled.
using CHandleRef in turn has the following drawbacks:
- additional tracking object allocated on the heap for each handle (but not for each copy). That makes CHandleRef unsuitable if you rapidly create and destroy thousands of handles. It's the one major drawback I admit freely
- twice the size. No real problem
- pass by value is bit more expensive than passing a handle by value.
- additional dependency
In the end I think it's 90% abot taste and style. Only with the remaining 10% I'd insist that class/library interfaces using handle wrappers like this are more elegant and usable, and once "reference counted" us understood, I can safely forget about so many things, which is my personal holy grail of software design.
At the sides, MFC in most cases opts to make the wrappers uncopyable. A proper decision design wise, but damn inconvenient.
Some of us walk the memory lane, others plummet into a rabbit hole
Tree in C# || Fold With Us! || sighist
|
|
|
|

|
peterchen wrote: The problem I try to solve is not passing, but returning and storing.
Returning is a form of passing. And generally speaking, you shouldn't be storing handles. There is a slim chance (depending on the type of handle) that the OS can decide to move it. If you kept the original handle, you will end up with a very random (meaning extremely difficult to debug) crash.
peterchen wrote: (1) Not all "Handle-Like things" have an DuplicateHandle.
One example: Registry keys (not technically kernel handles, you can open another handle to the same key, but you lose the access rights of the original HKEY)
Anything that is equivalent to HANDLE can be used in DuplicateHandle. In fact, some of the APIs for other types of handles actually make calls to DuplicateHandle. Yes, it will be less efficient than passing a reference to your handle value, but it will also be safer in some cases (actually, almost all cases).
peterchen wrote: (2) The solution is generic for all pointer-sized handles. Less code, less test cases, less things to know. A custom implementation for fonts would be very expensive (HFONT -> LOGFONT -> HFONT, or is there a better one?)
Your intensions aren't the problem. Unfortunately, when it comes to kernel objects, you can't treat them like any other pointer. If you don't follow the proper steps for creation/deletion for a given type of kernel object, you will easily cause resource leaks that will bog down your entire system (until you reboot). Your choices for things like this are to read the documentation very carefully and wrap those steps into your own custom classes, or to use libraries that already do it for you. MFC does the font stuff fairly well (though, it does take some getting use to).
peterchen wrote: (3) The kernel reference count isn't available (directly or indirectly) in user mode.
That is how it should be. You shouldn't care what the reference count is. The only time you really need to look at it is when you are debugging, and you can get to it then (through the debugger).
peterchen wrote: E.g. DuplicateHandle has two drawbacks:
It returns a new handle value (I tried XP SP2, file handle, DUPLICATE_SAME_ACCESS). So we can safely assume using DuplicateHandle takes longer and eats additional resources per copy.
Further, the copy operation could fail, which must be handled.
DuplicateHandle (and its equivalents) basically create a new pointer to the resources. You aren't going to use this method for things like passing the handle into a function to operate on the handle (say, to use it to draw something to the screen). An example of when you want to use it is when you want to have 2 threads drawing to the screen (each thread would have its own copy of the handle).
If the copy operation fails, it means something in the system went very wrong (e.g. you ran out of resources).
I don't question your motives behind this article (I actually like the direction you are thinking), it is just wrapping something that is already done by the OS (the reference counting) creates duplicate functionality and increases complexity (what happens if your reference count gets out of synch with the OS's?). Another way you could wrap handles is to create a method that automatically dupilcates it for you and returns a new wrapper (you probably wouldn't want to do that in the copy-constructor nor the copy-assignment methods though ... that would prevent you from passing the class by value, which you may want to do sometimes).
If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week
Zac
|
|
|
|

|
Zac Howland wrote: what happens if your reference count gets out of synch with the OS's
The shared_ptr references don't need to be in sync with the kernel. They key is the usgae guide: create, and assign, e.g. I'm using:
CHandleRef OpenLogFile() { ... }
The OpenLogFile method opens the handle and immediately assigns it to a CHandleRef. The raw handle is now "owned" by CHandleRef, meaning I must make sure it is not closed manually, or stored in raw form. As long as I guarantee this, my reference count will be on top of a single reference to the actual file object (I'm not sure how familiar you are with COM, but the same mechanism is used for reference counting across an apartment boundary.)
I agree that this requires some bit of "training", and maybe I find it easy only because I know smart pointers inside out from years of COM. But this pattern (both the idea and the code) is highly reusable, e.g. just two days ago for enumerating firewire devices. Two lines of code for an exception safe HDEVINFO (and another shared_ptr for the dynamic sized structures used in hardware enumeration)
I'm not trying to brush away your comments (even if it may sound like), I often notice that I "learn" something from such a discussion only a few weeks (even months) later.
Zac Howland wrote: you shouldn't be storing handles.
Sorry, I can't follow you here. The "behavior" of handkles is well defined. Of course I might accidentally close a handle behind the stores back etc. but code can't protect us from stupidity anyway.
What I'm trying to do is making write good code simpler. Most Windows bugs are in resource management. By associating the cleanup function with the handle there's one thing less to remember.
I've always been unhappy with the MFC solution, particulary because it requires you to read lot of MFC documentaiton carefully, and it doesn't interoperate with other libraries very well.
Zac Howland wrote: If the copy operation fails, it means something in the system went very wrong (e.g. you ran out of resources).
Agreed, if the DuplicateHandle faisl, you can probably shut down the app anyway. But error handling is an application aspect that cannot be decided by the library (CHandleRefT doesn't include any error handling. but it makes it much much easier)
Anyway, enjoy the weekend
Some of us walk the memory lane, others plummet into a rabbit hole
Tree in C# || Fold With Us! || sighist
|
|
|
|

|
I don't see the advantages of your approach:
- Implementation
Why do you use boost::shared_ptr? Seriously, all you need is a reference counter that indicates if a resource must be destroyed in the destructor.
-Design
Resource handling is 'partly managed' which is error-prone: Ownership is controlled by a flag that has to be set by the user. On the other hand, managed resources are converted automatically to unmnaged handles by operator HDL().
But maybe I have overlooked something?
Best wishes,
Roland Pibinger
|
|
|
|

|
There are definitely questionable design choices, the following is the motivaiton for taking them, I don't think they are "better" than some other options.
(1)
because boost provides exactly what I need, and reduces the implementation effort. You need:
- A class / struct for the shared resource itself
- The "smart pointer" class (whatever it is)
- A "plugin point" for the custom resource deleter
This takes me to three entities, one of which is visible to the user and needs utmost care in handling (I've written smart pointer like stuff before, it's nothing I wouldn't like to have thorughly tested in production code, and a C++ guru should look for pitfalls)
boost::shared_ptr provides just that: holding the reference count, and the handle, a fully tested reference counting pointer, and a custom deleter that is NOT a template parameter (which is important to avoid template infection of the using application)
(2)
It was not a design goal to completely isolate the client from GDI resource handling. I've pondered it a long time, and concluded it is not possible wihtout wrapping huge chunks of the windows API.
Rather, I wanted:
- a solution that can be integrated with any other library that can work somehow with raw handles.
- SIMPLIFY common resource handling problems
- Move the "How to delete" decision to the point where the resource is acquired
- low amount of code
Using the library can simplify resource handling, if you understand reference counted entities (not too simple, but very common), and understand Win32 GDI resource handling (which is IMO a necessity, unless you wrap the entire GDI API).
implicit cast to HANDLE type:
I was uneasy about the cast to raw handle, it's a tradeoff between comfort and bulletproofness. I opted for comfort, that's all. The alternative would be:
- a cast to "unspecified_bool_type" (as boost does) for the "Handle zero" check
- a HANDLET get() const member
I would prefer the latter if HANDLET could be a complex type. However, we are basically using void * / unspecified_type * here. In this case, I believe, the implicit cast is safe.
Also, since I want to integrate with "anything that takes raw handles", I cannot protect the client from accidentally deleting the raw handle with the wrong function or at the wrong time.
The core implementation is less than 2 dozen lines (not counting curly braces)
I think I stated this before - but the idea of this article was to privde a practical example for my previous one, and see how/if it could solve a long-nagging problem (reference counting for handles).
we are here to help each other get through this thing, whatever it is Vonnegut jr. boost your code || Fold With Us! || sighist | doxygen
|
|
|
|

|
How does this object play with SelectObject, a function which changes the delete requirements of an object.
For Example
CSmartPenHandle pen( ::CreatePen( PS_SOLID, 1, RGB(0,0,0) ) );
// now the pen should be deleted by SelectObject
// I think that ref counting smart pointers are good, but not for DCs,
// there too complex a resource for that. You don't want to leave
// them lying around for sure and ref counting might let that happen
HDC hdc = ::GetDC( hMyWnd );
::SelectObject( hdc, pen.GetWin32Handle() );
// pen now mustn't be deleted. Especially if hdc is a class or window dc.
// if it is neither then typically you'd select the return value back in,
// but if you don't then ReleaseDC deletes the pen, and your destructor
// will fail.
Note that this is just a thought excersise. The example is great as it stands, but i'm simply trying to give an example of why GDI objects in particular don't really lend themselves to smart pointers.
|
|
|
|

|
Stewart Tootill wrote:
Note that this is just a thought excersise.
Actually, it is not. It is the weak point of my article
I was considering this when writing, but I finally left it out for several reasons.
You could use a "DC Selector" helper (see below), but ultimately, I don't think any amount of code can circumvent all possibilities to shoot yourself in the foot. In the end, you will have to follow some rules.
The basic idea would be to (a) make sure the object is deselected (e.g. using SaveDC/ReleaseDC, possibly with a scope guard to be safe), and (b) hold a strong reference to the object until it is deselected
I wouldn't even use HandleRef for temporary objects created in the WM_PAINT itself, they original idea was for GDI resources you "keep around" instead of reinitalizing them again and again. But the following could help a bit (but it's just a rough outline):
template <class HANDLE>
struct CDCSelector
{
CHandleRef<HDC> dc;
HANDLE oldHandle;
CHandleRef<HANDLE> handle;
CDCSelector(CHandleRef<HDC> _dc, CHandleRef<HANDLE> h) : dc(_dc), handle(h)
{
oldHandle = 0;
if (handle)
oldHandle = (HANDLE) ::SelectObject(dc, h);
}
void Restore()
{
if (handle)
{
::SelectObject(dc, oldHandle);
handle = CHandleRef<HANDLE>();
}
}
~CDCSelector() { Restore(); }
};
(It would require special CDC support, since DC's come with two destructors - ReleaseDC and DeleteDC, and you would still need to do the nesting correctly. So it's not perfect either. The only "bulletproof" solutions I see would require a complete wrapping of the DC handle, which I would dislike)
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
I think that the two destruction methods for DCs (there are more than two if you start to include DirectDraw/3D/Show and GDI+ but that may be taking things two far) are the best reason for not attempting to wrap DCs in classes.
Were you to attempt to do this however, MFCs approach would probably be a good guide. There are three DC classes (plus some other ones for printing that don't matter in this case). CPaintDC gets its DC by calling BeginPaint and releases it with EndPaint and is constructed with a window handle. CClientDC/CWindowDC use the GetDC/GetDCEx functions and ReleaseDC to release them, and straight CDC (which is the base class, but obviously the derived classes override the destruction) which uses DeleteDC to delete the DC which covers most (but not all - see previous comment about DirectX and GDI+) other cases.
Its really a shame that one of the trickiest things to wrap in C++ is also one of the hardest to avoid. I remember starting SDK programming for real on windows having previously used other systems (most notably BeOS) and being thoroughly confused by these DC things. But you can't write even the most trivial GDI application without encountering them.
|
|
|
|

|
Please allow me to reply in a single post
I don't think virtual is to high of a cost - after all, the bost::shared_ptr solution comes in even higher (and would have made it a no-go for the machines MFC 1.x was intended for)
However, the "battlefield", as I see it, is not virtual vs. templates, but Copy Construction and Assignment.
Since the MFC approach does not provide these, I am forced to pass around CDC * or CDC &, so the wrapper trades in management of one resource (GDI) for another (C++ object lifetime) which is a beast of it's own, and I lose many advantages of scoping.
Reference counting does not plug all holes (SelectObject, as you pointed out, is the gaping barn door, and the template suggested is more a fix than a solution), but it plugs many more holes than it opens, and reduces the "mental overhead" of using GDI resources.
Both the virtual destructor, and the "custom deleter" achieve one thing: associating the destruction policy with the resource at time of acquisition. However, the virtual-only solution prohibits common functionality (passing as argument or return value) and moves the complexity only up one level in the hierarchy.
I would like to emphasize that I don't see the solution presented here as the only one. It is neither perfect, nor the most simple one. But I consider it well balanced, and surprisingly simple once you have "accepted smart pointers in your life".
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
I just updated the article, including a CDCRef (in a separate, but single class).
It was more a exercise to see if DC's could be fit into the HandleRef model, but I'm happy with the results.
let me know what you think
we are here to help each other get through this thing, whatever it is Vonnegut jr. boost your code || Fold With Us! || sighist | doxygen
|
|
|
|

|
I haven't had time to try this, bit I thought you might be able to replace the bool delete on release flag with a template argument and use specialisation to resolve it. Sure it would make the code bigger (but who cares, memory is cheap and hopefully all this stuff gets inlined anyway) but typically you would never pass a non-const value into that field. The type of delete should almost always be known at compile time. And writing a function that can take a dynamic value once you've done it with specialisation is easy. That way the extra cost (small until you start allocation alot of pens with it, or trying to walk thousands of registry keys) is only there for those that need it.
|
|
|
|

|
you mean CHandleRef<HANDLE, bool> ?
I don't think that's a good idea, since all functions taking such a HandleRef would have to be templates, too. (Or am I missing something? your Stewart Tootill wrote:
And writing a function that can take a dynamic value once you've done it with specialisation is easy sounds like I do...)
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
Maybe a common base a policy specialisation would solve that
class CGdiHandle
{
public:
/* other stuff ommited */
virtual ~CGdiHandle() = 0; // a virtual too high a cost?
protected:
HGDIOBJECT GetHandle() const { return m_hGdiObject; }
private:
HGDIOBJECT m_hGdiObject;
};
struct FreeObject
{
static void FreeObject( HGDIOBJECT handle ) { ::DeleteObject( handle ); }
};
struct DontFreeObject
{
static void FreeObject( HGDIOBJECT /*unused*/ ) { }
};
template < class deletePolicy >
class CGdiHandleImpl : public CGdiHandle
{
public:
virtual ~CGdiHandleImpl() { deletePolicy::FreeObject( GetHandle() ); }
};
template < bool bDeleteObject >
class CGdiSmartPtr : public CGdiHandleImpl< FreeObject >
{
};
template <>
class CGdiSmartPtr : public CGdiHandleImpl< DontFreeObject >
{
};
Then use CGdiSmartPtr when creating them but functions that only need references, so don't need the concrete type, can accept a reference to the first abstract class, and don't need to be templated. Its probably a lot of effore though
|
|
|
|

|
CAutoPtr newFont(new CFont);
...
// in copy constructor or assignment operator etc
left.newFont = right.newFont; // Exchange ownership, whoever owns it ultimately, the GDI object will be deleted in destructor
You can certainly extend MFC to suit your case, but never the less MFC has often provide a good ground to start with.
You may also use specialize template instead of functor, to have compiler automatically choose which API to call, when closing a handle.
Good day.
|
|
|
|

|
I guess this is partly a question of taste (antd tools you know inside out). I am still convinced MFC has to many drawbacks, and even auto_ptr cannot save that:
- auto_ptr does not share, but transfer ownership. I still have to figure out who gets it last.
- auto_ptr cannot handle temporary objects, or pointers-to-member
The interface provided by MFC is not simpler than the raw API interface, it requires me to remember more things (That's it's main failure). It works great in an OnPaint function, but beyond it's just silly. Dragging around the deletion policy in a separate variableis silly. Detaching and reattaching the HFONT in a CFont-Member-Setter is silly. (And all functions of MFC expecting a CGdiObject * instead of a HGDIOBJECT is silly, too. But that's another topic completely).
If this sounds like a rant against your favorite method, I am sorry. I am currently in the mood
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
1. When sharing HANDLE, only 1 auto pointer should hold the resource and expose (share?) via method or attribute, this auto pointer will release the HANDLE gradually. Is it necessary to known exactly which object holds it? Maybe.
2. You can easily extend auto_ptr (instead of create new class) or simply use auto_ptr_ref to support temporary etc. And in ATL 7 above, there is a class call CAutoPtr.
3. Usually in MFC we try to "remember" (instead of understand?) which class, which method and when. While API you do the same but a "series of APIs". MFC does this for as it wrap "series of APIs" into one call. Example is when main frame resize, how size is calculated amongs various sub-controls.
4. You may stick to MFC default Attach/Detach, or you can extend it with one call, even automatic call. Remember MFC provide a common ground, not a silver bullet. There is no one framework suit all.
Of course, nothing stop you from going deep down to API, or simply WTL.
Good day.
|
|
|
|

|
1) at least you have to know that the one owning it lives longest.
2) didn't know about auto_ptr_ref, thanks for pointing out!
However (you knew that was coming ), it only tries to fix what is already broken: auto_ptr, compared to a refcounted smart pointer, trades of some performance win for quite some additional complexity. I think itwas a bad move to include auto_ptr as the only smart pointer in the STL. If at all, it saved "them" a few tricky design decisions (thread safety? where to store the ref count?)
3) TW wrote:
Usually in MFC we try to "remember" (instead of understand?) which class, which method and when.
This perfectly describes my main "issue" with MFC, and nowhere this is standing out clearer than with the MFC resource handles (Embedded COM object handling, maybe)
Classes should wrap concepts, not series of commands. Classes should not be silver bullets killing one kind of problem perfectly if shot at the right angle. Rather, classes must be 1) unbreakable in almost every situation and 2) simpler to use than the things they wrap. A kind of Kalashnikow: sturdy, reliable, and usable by everybody who read "programming for dummies".
4) That's basically what I am doing when writing MFC code: use API calls, and using tight attach/detach. Horrible for an MFCian, but it allows me to live with one API intrically known, not two.
The motivation for this article being: MFC did what was appropriate at it's time, for it's purpose. But we can do better, and with the tools available, in much less lines of code than MFC does.
Enjoy
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
Talking about resource intensive application, VISIO is certainly one of its kind. Guess what, MFC is used heavily in this VISIO product, you can use Spy++ to check it out.
I won't say MFC is perfect, but I think till today, it is still the best C++ framework available on Windows. It's really up to you how much you want to extend it. We can't keep complaining about MFC "as-is" but does not extend it, right? You can also check out Stingray Objective Studio to see how far MFC can go, just don't be surprise.
Unfortunately MS has no plan to further improve MFC, like Delphi VCL.
Nice talking to you, bye.
|
|
|
|

|
You should try the QT framework from Throlltech, they gave me a productivity boost over MFC, ATL etc. etc. and they are portable to Mac and linux!!!!!
I have found MFC's one of the worst frameworks around.
|
|
|
|

|
We are using Qt here as well. Comparing with Qt for Windows, MFC is not designed to be OS indepedent, also MFC is much easier to understand and fast.
|
|
|
|

|
MFC did what was appropriate at it's time, for it's purpose.
I have to disagree with this. MFC was obviously flawed at birth. They took the Model-View-Controller scheme from Smalltalk and broke it by combining the model and controller. Consequently, unless you're very disciplined, the View and Document classes end up as a monolithic disaster, where very little of the code is reusable because the model and UI are all mixed together. This is my main gripe with MFC - it encourages appallingly bad program design.
> I think it was a bad move to include auto_ptr as the only smart pointer in the STL.
I think *everyone* on the Standards committee agrees with that. I heard that the smart pointers were stuffed up because they just ran out time. (Likewise the omission of copy_if). Note that shared_ptr was the first thing admitted into C++0x.
|
|
|
|

|
Don Clugston wrote:
I think *everyone* on the Standards committee agrees with that.
heh! Me agreeing with the Standards commitee on STL
MFC: The first thing I did was drop their Doc/View-Model, (or simply work around it) and do the stuff "my way". I was never sure if this was "just me" or a general flaw.
For the rest (i.e. trying to abstract the Windows API) it isn't to bad considering the time it was made, hough a few choices could have been better (and GDI wrapper handles are broken IMO)
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
TW wrote:
You may also use specialize template instead of functor, to have compiler automatically choose which API to call, when closing a handle.
I tried that initially, but the compiler expects an instantiation of the function, and the linker complainsfor a just-header-library. I guess this is just a compiler thing (should it work according to the standard?)
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
You have this fixed in your downloadable source files, but the article refers to HFONT when implementing the generic handle template.
explicit CHandleRef(HFONT font, bool deleteOnRelease)
Not a huge deal, but potentially confusing to beginners.
Thanks for the good article. If anything, your writing style, and step-by-step explanation, is what makes it so enjoyable.
|
|
|
|
|

|
You are evil, don't you know?
The very moment I ponder which project to get back to next, you remind me of all the irks I have with registry wrappers. Such things should be banned
But since you asked...
Your article is one of the two I consider closest to my expectations (sorry, this sounds like a "diva copmpliment", but it's just I'm rarely satisfied, even with my own code). The only place I'd (now) use boost, would be an intrusive_ptr for the PIMPL idiom.
In general, a registry wrapper would have three API layers:
(1) Wrapping the Windows API in type-safe functions using a CHandleRef<HKEY> instead of HKEY. Open, Get, Set, Get vector of values names, childs, etc. Should be very close to the Win API in naming, argument order, etc. However, I'd use a string class for it, and it would be CString for personal preference.
(2) An extende registry key that, like yours, tracks the whole path, and provides simple "navigation". This would also be the layer that allwos using another storage (XML, Property Bag, etc.)
I would, however, use a different access rights management: keys are opened with the least REGSAM required, and track which access rights were granted and not. When another REGSAM is desired, it tries to "bump" the key to the combined requirements. This could completely isolate the user from pondering his necessary rights, without sacrificing performance or restricted environments.
(3) Data Binding to Controls (like your RegDDX), and Data Classes that "act" like a registry value. (i.e. you can assign a CString, get a value of certain type, etc.) The data classes should allow to easily build structures containing configuration values.
Only layer (1) would have to be high performance. The others can trade off quite some speed & memory for convenience.
Damn now you got me ticking...
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
Very well written, thanks (like your previous article)!
I like to read those contributions, which discuss a problem and show the developement of a solution. Especially when it comes to templates, it is often hard to understand the final solution, whereas it is much more instructive to follow the steps evolving from special to general.
I'd like to ask you for one more explaination: How did you get rid of the delete-operator? Where is the delete actually performed, which you removed from the custom-DELETER?
Christof
|
|
|
|

|
I assume you are asking about the step from snippet (5) to (6)?
first, check the declaration of the smart pointer type: it has changed from shared_ptr<HANDLE>> (representing a HANDLE *) to shared_ptr<void> (representing a void *)
All the initial versions did allocate a new HANDLE object on the heap, store the handle itself there, and a pointer to that handle in the smart pointer.
The last version stores the handle in the smart pointer itself - as void *. Now this works only because all the handle types I'm concerned about can be stored as void *. But this sacrifice of flexibility has two advantages: better performance, and the custom deleters are simpler to write.
I could have done this step earlier, but I wanted to carry on the flexible solution as far as I could.
Helped?
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
Yes, now I got it! I had overlooked, that you had also removed the new operators. This gave me then the clue, what happend from (5) to (6).
Thanks, Christof
|
|
|
|

|
It appears that I have an older version of boost maybe (1.27.0)? But I got the following compile error in VC6 & VC7:
-------------------Configuration: ResHandle - Win32 Debug--------------------
StdAfx.cpp
ResHandle.cpp
E:\alchdev\examples\HandleRef\ResHandle.cpp(87): error C2440: '?': cannot convert from 'const boost::shared_ptr' to 'bool'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
E:\alchdev\examples\HandleRef\ResHandle.cpp(87): fatal error C1903: unable to recover from previous error(s); stopping compilation
Error executing cl.exe.
ResHandle.exe - 2 error(s), 0 warning(s)
Maybe:
#include
#if BOOST_VERSION < 103100
LAUNCH_WMD()
#endif
Todd Smith
|
|
|
|

|
that's really weird, boost explicitely opted for if (pointer) for the NULL pointer check, so the code should compile ok:
{ return m_ptr ? *m_ptr : NULL; }
internally, boost::shared_ptr uses a cast to "unspecified bool type" (actually, a function pointer), to provide the auitomatic cast without the "usual problems" (whatever they may be)
I'm on VC6 SP5 (didn't bother to fire up VC7 ) and boost 1.30.
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
boost 1.31.0 worked.
Todd Smith
|
|
|
|

|
Very nice article. This is an elegant solution to a problem i've faced many times.
You're one microscopic cog
in his catastrophic plan...
|
|
|
|

|
The second 5 in a cople of weeks !!!
I understand that the subject is "boost", but many concepts, here, does not stictly depend on boost. Boost is a huge library that may be not the case to include if you only need shared_ptr (thay can be easilly coded in a 100 lines header), but the way you solved the sharing of handles problem is really good.
I addressed the problem with a more "policy like" approach here[^], but this makes me reconsider certain choices !!
2 bugs found.
> recompile ...
65534 bugs found.
|
|
|
|

|
You are absolutely right, using a reference counter isn't new, there are a few articles on CP here (and now, reading your article I remember seen it before ).
A few things came together in writing the article: I've long pondered the problem and knew my requriements for a solution, I needed a "quick fix" a few days ago and could hack it together in minutes using shared_ptr, I found the process of turning it into a solution interesting enough for another article, and I could feed of the success of my previous one. It's not "very boostish", as the public interface of CHandleRef does not expose anything about boost, it could be reimplemented with any other smart pointer imlementation.
So the idea is indeed implementing a known concept with as few code as possisble, the core is less than 30 lines of actual code. It's not as flexible a a policy design (but I have some "issues" with them - see my response above about Loki), but doing the job.
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
Good article. I'm wondering how this idea meshes with WTL which also has a 'bShouldDelete' parameter on creation of any of the 'handle' classes. I think your code could work really well as a WTL extension.
> Second, we can make both the Handle type and the Deleter a template parameter. it's simple for the Handle, but we can't specify a function as template argument.
FYI: Actually you can. Function pointers are permissible as template arguments. It's a bit bizarre, but it's in the standard. It won't work on all compilers (eg, VC6, DMC) and functors are far more useful anyway.
|
|
|
|

|
I don't think WTL would like the dependency on boost. However, an "#ifdef boost (use this stuff too)" would certainly be possible.
I consider the concept (using a reference-counted entity with a custom deleter) the minimum for wrapping handles. IIRC the CSmartHandle class (here on CP, mentionend also in a post below) does that with it's own code base, so it might be easier to integrate.
Don Clugston wrote:
Actually you can. Function pointers are permissible as template arguments
I thought so much. I threw out the "(I don't know if it's just my compiler, or a C++ thing)" line because the article is long enough already. But I'll fix the comment with the next update.
we are here to help each other get through this thing, whatever it is Vonnegut jr.
sighist Fold With Us! || Agile Programming | doxygen
|
|
|
|

|
Please continue the good work.
John
|
|
|
|
|
 |
|
|
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
Using boost, we can write "almost perfect" wrappers for GDI and other resource handles, in a few lines of code.
| Type | Article |
| Licence | |
| First Posted | 4 Oct 2004 |
| Views | 136,800 |
| Bookmarked | 54 times |
|
|