Skip to content

Instantly share code, notes, and snippets.

@Reedbeta
Created February 8, 2018 20:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Reedbeta/93fe9820442587df3192e74e7444a089 to your computer and use it in GitHub Desktop.
Save Reedbeta/93fe9820442587df3192e74e7444a089 to your computer and use it in GitHub Desktop.
Auto-releasing wrapper for COM pointers
// Auto-releasing wrapper for COM pointers
// Feel free to use this for whatever, I don't care
template <typename T>
struct comptr
{
T * p;
comptr(): p(nullptr) {}
comptr(T * other): p(other)
{ if (p) p->AddRef(); }
comptr(const comptr<T> & other): p(other.p)
{ if (p) p->AddRef(); }
comptr(comptr<T> && other): p(other.p)
{ other.p = nullptr; }
void release()
{ if (p) { p->Release(); p = nullptr; } }
~comptr()
{ release(); }
comptr<T> & operator = (T * other)
{ release(); p = other; if (p) p->AddRef(); return *this; }
comptr<T> & operator = (const comptr<T> & other)
{ release(); p = other.p; if (p) p->AddRef(); return *this; }
comptr<T> & operator = (comptr<T> && other)
{ release(); p = other.p; other.p = nullptr; return *this; }
T ** operator & () { return &p; }
T * operator * () { return p; }
T * operator -> () { return p; }
operator T * () { return p; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment