如何使用C ++标准智能指针与Windows HANDLEs? [英] How to use C++ standard smart pointers with Windows HANDLEs?

查看:103
本文介绍了如何使用C ++标准智能指针与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.

到目前为止,可能性:


  1. 为HANDLEs创建一个包装类,并像这样使用: unique_ptr< new CHandle(h)> ; 。这几乎使 unique_ptr< T> 本身无用。

  2. 使用 HANDLE 类似 unique_ptr< T> 的特定智能指针类。

  1. Create a wrapper class for HANDLEs and use it like this: unique_ptr<new CHandle(h)>. This pretty much makes the unique_ptr<T> itself useless.
  2. Use HANDLE specific smart pointer class that resembles unique_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆