jah*_*aho 6 c++ com smart-pointers c++11
我正在尝试使用智能指针在我的类中保存 COM 对象,同时避免 ComPtr。是否可以为此目的使用 unique_ptr ?
我对智能指针很陌生,到目前为止我有点困惑。请考虑以下简化代码:
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
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:getter 应该返回什么(原始指针或 unique_ptr 实例)以及如何将 unique_ptr 传递给创建资源的函数?
我正在尝试使用智能指针在我的类中保存 COM 对象,同时避免
ComPtr.
解决方案是使用ComPtr. 如果您正在使用 COM 对象unique_ptr,ComPtr那么它是一个糟糕的替代品。
ComPtr提供用于处理 COM 对象和IUnknown. 例如,它内置了对安全接口查询的支持(通过As成员函数)。它也可用于 COM 中常见的 out 参数(通过GetAddressOf函数)。