Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-05-03 07:41:25

From: "Andrei Alexandrescu" <andrewalex_at_[hidden]>
> "Greg Colvin" <greg_at_[hidden]> wrote in message
> news:
> > And, referring back to a point you made about HANDLE causing
> > shared_ptr<HANDLE> to different things (like files and windows)
> > to be assignable, I think the real problem is that Win32 uses
> > a void* handle to point to all kinds if things, and has many
> > functions that work on generic HANDLEs, as well as many functions
> > that work only on specific HANDLEs. It's a mess to untangle,
> > but can be done with a wrapper class for the generic HANDLE and
> > derived classes for more specific HANDLEs.
> Inheritance doesn't model things properly here. The different types of
> handles in Windows are unrelated and do not sport much commonality and
> little variation. Consequently, a hierarchy is not useful here.

Not really. Some Windows handles do form a hierarchy. For instance, many GDI
handles (HGDIOBJ) are destroyed with DeleteObject, and many different HANDLE
types are all destroyed with CloseHandle. The problem is that, to keep the
API C-compatible, all bases in the hierarchy are pointers to void (for
instance HBRUSH is __hbrush* but HGDIOBJ is void*.)

In any event, the lack of type safety here is Windows' problem.

> Different types of handles should map to different, distinct types.

Agreed. shared_ptr<HANDLE> doesn't make sense anyway. I rarely need to
allocate HANDLEs on the heap. ;-)

My preferred way to make a smart handle is:

class handle
    HANDLE h_;
    detail::shared_count n_;


    explicit handle(HANDLE h): h_(h), n_(h, ::CloseHandle) {}

(Or you could exploit the fact that a HANDLE is a void* and use a
shared_ptr<void> but still keep it safely wrapped in a dedicated class.)

I've never recommended using shared_ptr for general resource management.
shared_ptr models only pointers and encapsulates only
allocation/deallocation details. Nothing more. It's true that people tend to
find clever ways to (ab)use it.

Boost list run by bdawes at, gregod at, cpdaniel at, john at