How to use C++ standard smart pointers with Windows HANDLEs?
inspired by Alexander Drichel's solution, here is even shorter
std::unique_ptr< HANDLE, decltype(&CloseHandle) > uniqueHandle( nullptr, CloseHandle );
Works in MSVC 2010. Note that you need to specify '&' for the function name in decltype() to deduce a pointer-to-function type.
The question can be extended for COM IUnknown pointers - can CComPtr be replaced by any of the standard smart pointers?
Yes. You don't specialize std::default_deleter
, you simply replace the deleter type.
struct COMDeleter {
template<typename T> void operator()(T* ptr) {
ptr->Release();
}
};
unique_ptr<IUnknown, COMDeleter> ptr; // Works fine
The same principle applies to shared_ptr
and indeed, to HANDLE
.
Create a specific smart pointer class, won't take long. Don't abuse library classes. Handle semantics is quite different from that of a C++ pointer; for one thing, dereferencing a HANDLE makes no sense.
One more reason to use a custom smart handle class - NULL does not always mean an empty handle. Sometimes it's INVALID_HANDLE_VALUE, which is not the same (actually -1).