使用std :: unique_ptr管理COM对象 [英] Using std::unique_ptr for managing COM objects

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

问题描述

我正在尝试使用智能指针将COM对象保留在我的班级中,同时避免使用ComPtr。



我对智能指针还是很陌生,到目前为止,我有点困惑。请考虑以下简化代码:

  class Texture 
{
private:
struct ComDeleter
{
operator()(IUnknown * p)
{
p.Release();
删除p;
}
}

ID3D11Texture * m_dumbTexture;
std :: unique_ptr< ID3D11Texture,ComDeleter> m_smartTexture;

public:
ID3D11Texture * getDumbTexture()const {return m_dumbTexture; }
ID3D11Texture * getSmartTexture()const {return m_smartTexture.get(); } //这里返回什么?
}

Texture :: Texture():
dumbTexture(NULL),
smartTexture(nullptr)
{
}

Texture :: init()
{
D3DX11CreateTexture(& m_dumbTexture);
D3DX11CreateTexture(& m_smartTexture.get()); //错误:&要求r值
}

所以我的问题是:getter应该返回什么(原始指针或unique_ptr实例),以及如何将unique_ptr传递给创建资源的函数?

解决方案

< blockquote>

我正在尝试使用智能指针将COM对象保留在我的类中,同时避免使用 ComPtr


解决方案是使用 ComPtr 。如果使用COM对象,则 unique_ptr 不能很好地替代 ComPtr



ComPtr 提供了用于处理COM对象和 IUnknown 的特殊功能。例如,它内置了对安全接口查询的支持(通过 As 成员函数)。它也可以与COM中常见的out参数一起使用(通过 GetAddressOf 函数)。


I'm trying to use smart pointers to hold COM objects in my class while avoiding ComPtr. Is it possible to use unique_ptr for this purpose?

I'm quite new to smart pointers and so far I'm a bit confused. Please consider the following simplified code:

class Texture
{
private:
    struct ComDeleter
    {
        operator() (IUnknown* p)
        {
            p.Release();
            delete p;
        }
    }

    ID3D11Texture* m_dumbTexture;
    std::unique_ptr<ID3D11Texture, ComDeleter> m_smartTexture;

public:
    ID3D11Texture* getDumbTexture() const { return m_dumbTexture; }
    ID3D11Texture* getSmartTexture() const { return m_smartTexture.get(); } // what to return here?
}

Texture::Texture() :
    dumbTexture  (NULL),
    smartTexture (nullptr)
{
}

Texture::init()
{
    D3DX11CreateTexture(&m_dumbTexture);
    D3DX11CreateTexture(&m_smartTexture.get());  // error: '&' requires r-value
}

So my problems are: what should the getter return (raw pointer or unique_ptr instance) and how can I pass the unique_ptr to function which creates the resource?

解决方案

I'm trying to use smart pointers to hold COM objects in my class while avoiding ComPtr.

The solution is to use ComPtr. unique_ptr is a poor substitute for ComPtr if you're working with COM objects.

ComPtr provides specialized functionality for working with COM objects and IUnknown. For example, it has built in support for safe interface querying (via the As member function). It is also usable with out parameters, which are common in COM (via the GetAddressOf functions).

这篇关于使用std :: unique_ptr管理COM对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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