Manage Object Lifetime Using Reference Counting on Interface Pointers (C-C++)
Like other COM technologies, MSXML uses reference counting to manage the lifetime of a DOM object. A reference count is a number indicating the state of an object. Whenever an object is created or its reference is duplicated, the reference count of the object is incremented. When an object is no longer needed, its reference count is decremented. A positive reference count means the object is usable. When the reference count becomes zero, the object is unusable, and most likely removed from the process memory.
When you use raw COM interface pointers in MSXML, you need to handle reference counting on the interface pointers explicitly. If you do not do this properly, your applications are likely to have memory leaks or to encounter access violations because objects or interface pointers were incorrectly made unusable. Even when you use smart pointer class wrappers that automate memory management, a good understanding of reference counting helps ensure that you use these wrapper classes and templates correctly.
The following are general guidelines for handling reference counting when using MSXML:
Call the
AddRef
method on the interface pointer to increment the reference count when its reference is duplicated.Call the
Release
method on the interface pointer to decrement the reference count when the interface pointer is no longer needed, or is to be reused in a different context.
When you create or obtain an object by calling, for example, IXMLDOMDocument::createNode
, IXMLDOMNode::appendChild
, or CoCreateInstance
, the object's reference count is already incremented before the function or method returns. It is your responsibility to release the object when you are done using it. If you duplicate the reference of an existing object, you need to call AddRef
explicitly on the new interface pointer. This tutorial presents a hands-on illustration of these issues.
This project uses or creates the following files.
Component | Description |
---|---|
Source: refCount.cpp | Creates an XML document using several DOM objects. |
Output | This is the output you should get when you build and run the refCount project. |
To create the refCount Visual C++ Project
- Create a Win32 console application in Visual C++. For detailed instructions on how to do this, see Set Up My Visual C++ Project. Name the project LoadDOMRawProj.
Next, we'll add the source code for this project.
Other Resources
"The Rules of the Component Object Model" (https://go.microsoft.com/fwlink/?LinkId=8320)