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?
p.Release(); delete p;is wrong: COM objects destroy themselves on the lastRelease(). - James McNellisdelete pnecessary? Looks like I've been reading some wrong tutorials. - jahodelete pis very wrong. What guarantee do you have that the COM object was allocated with C++'snew, and out of the same heap that your C++ library sets up for you? (hint: definitely not the case for DX objects). A major reason why COM objects manage their own lifetimes is because they are the only ones that know the correct way to deallocate themselves. - Euro Micelli