如何使用_com_ptr_t? [英] How do I use _com_ptr_t?

查看:268
本文介绍了如何使用_com_ptr_t?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个拥有 D3DDevice 的课程:

Say I have a class that owns a D3DDevice:

class Thing
{
public:
    Thing()
    {
        D3D11CreateDevice(..., &device, ...);
    }
    ~Thing()
    {
        device->Release();
    }
private:
    ID3D11Device* device;
};

根据我的理解,我可以使用 _com_ptr_t 以确保对象被删除,而不必在析构函数中显式调用 Release()。问题是,我不能弄清楚模板的正确语法。

From what I understand, I can use _com_ptr_t to ensure that the object gets deleted without my having to explicitly call Release() in the destructor. The problem though is that I can't figure out the correct syntax for the template.

我几乎找不到任何关于 _com_ptr_t ,我能找到的最接近的答案是这个(日语)一个。按照语法,我得到一堆编译器错误:

I could find hardly any information on _com_ptr_t, and the closest thing I could find to an answer was this (Japanese) one. Following the syntax there, I get a bunch of compiler errors:

private:
    //ID3D11Device* device;
    _com_ptr_t <_com_IIID<ID3D11Device, &__uuidof(ID3D11Device)>> device;

error C2143: syntax error : missing ';' before '<'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2238: unexpected token(s) preceding ';'
error C2065: 'device' : undeclared identifier

顺便说一句,我可以使用它从函数返回COM指针,并确保它们在离开调用者范围时被删除,是吗?

By the way, I can use this to return COM pointers from functions and ensure that they get deleted when they leave the caller's scope, right?

推荐答案

通常有两种方式来处理COM智能指针,我会推荐:

There are usually two ways of dealing with COM smart pointers that I would recommend:

1)你可以#import相应的类型库,它将基于_com_ptr_t自动生成智能指针类型。

1) You can #import the appropriate type library, which will auto generate smart pointer types based on _com_ptr_t.

2)你可以使用CComPtr模板在一个智能指针中的原始COM指针,通过自动AddRef / Release调用来处理资源管理,但不会给你很多其他。

2) You can use the CComPtr template to wrap your raw COM pointer in a smart pointer that takes care of the resource management via automatic AddRef/Release calls, but doesn't give you much else.

因为我是一个小懒,通常我不介意由 #import 自动生成的包装器的隐式开销,我通常使用1)。使用这种方法的一个最大的好处是, #import 机制还生成函数包装器,使COM函数看起来更像正常函数,具有适当的返回类型和翻译 HRESULT _com_error 异常对象。 IMHO,它倾向于改进C ++ COM代码中的控制流。

Because I'm a little lazy and normally I don't mind the implicit overhead of the wrapper auto-generated by #import, I usually use 1). One of the big benefits of using that approach is that the #import mechanism also generates function wrappers that make COM functions look more like normal functions with proper return types and a translation of the HRESULT to _com_error exception objects. IMHO that tends to improve the control flow in C++ COM code.

这篇关于如何使用_com_ptr_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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