如何使用C ++标准智能指针与Windows HANDLEs? [英] How to use C++ standard smart pointers with Windows HANDLEs?
问题描述
我想知道是否有一种方法可以使用Windows HANDLEs使用 unique_ptr< T>
?
I was wondering if there is a way to use unique_ptr<T>
with Windows HANDLEs?
正在考虑用 handle_trats
替换调用 CloseHandle $的特殊
std :: default_delete
c $ c>。问题是 HANDLE
定义为 void *
unique_ptr< void>
不会编译为 sizeof(void)
未定义。
I was thinking to replace the std::default_delete
with specific handle_trats
that calls CloseHandle
. The problem is that HANDLE
is defined as void*
unique_ptr<void>
won't compile as sizeof(void)
is not defined.
到目前为止,可能性:
- 为HANDLEs创建一个包装类,并像这样使用:
unique_ptr< new CHandle(h)> ;
。这几乎使unique_ptr< T>
本身无用。 - 使用
HANDLE
类似unique_ptr< T>
的特定智能指针类。
- Create a wrapper class for HANDLEs and use it like this:
unique_ptr<new CHandle(h)>
. This pretty much makes theunique_ptr<T>
itself useless. - Use
HANDLE
specific smart pointer class that resemblesunique_ptr<T>
.
你认为是更好的选择?你会建议什么?
What do you think is better choice? What would you suggest?
问题可以扩展为 COM IUnknown
指针 - 可以 CComPtr
被任何标准的智能指针替换?
The question can be extended for COM IUnknown
pointers - can CComPtr
be replaced by any of the standard smart pointers?
推荐答案
对于COM IUnknown指针 - 可以用任何标准的智能指针替换CComPtr
?
The question can be extended for COM IUnknown pointers - can CComPtr be replaced by any of the standard smart pointers?
是的。您不需要专门化 std :: default_deleter
,您只需替换删除类型。
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
同样的原则适用于 shared_ptr
并且 HANDLE
。
The same principle applies to shared_ptr
and indeed, to HANDLE
.
这篇关于如何使用C ++标准智能指针与Windows HANDLEs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!