3

We have some code that uses MSXML, and does this to create the XML document object:

MSXML2::IXMLDOMDocumentPtr  doc_in;

doc_in.CreateInstance("Msxml2.DOMDocument.6.0");

Once we're finished with doc_in, how do we destroy it? Is it just automatically destructed when doc_in goes out of scope, or what?

Colen
  • 13,428
  • 21
  • 78
  • 107

2 Answers2

3

If IXMLDOMDocumentPtr is a smart pointer (as it looks like) then it will take care of calling doc_in.Release() for you.

Vagaus
  • 4,174
  • 20
  • 31
  • What if I was using a `IXMLDOMDocument *` instead of an `IXMLDOMDocumentPtr `? Would that mean a different answer? I'm trying to get my head around COM... – Colen Apr 20 '11 at 03:32
  • Sure. In COM you are responsible for tracking COM interface usage. For that you use AddRef() and Release() calls on the interface pointer. If you are using "raw" pointers you need to call Release() when you are not using the pointer any more (not that AddRef() will be called for whoever handled the pointer to you - for instance QueryInterface()). – Vagaus Apr 20 '11 at 12:13
3

COM object lifetime management builds on reference counting via IUnknowns methods AddRef() and Release(). For details see "Using and Implementing IUnknown", in particular "Rules for Managing Reference Counts".

On top of that smart pointers are used, most commonly ATLs CComPtr/CComQIPtr and _com_ptr_t.

So, if you're dealing with a plain pointer to a COM instance, you have to Release() manually to relinquish ownership.
If you have a smart pointer to a COM instance, the Release() should be done for you when the smart pointer instance goes out of scope - but to be sure take a look at the documentation for the actual smart pointer class you are using.

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236