import and Smart Pointers


#import and Smart Pointers

These two lines are included in all our C++ routines that use any of the DOM interfaces:

 #import <msxml4.dll> using namespace MSXML2; 

This is a Visual C++ compiler directive that tells the compiler we're going to use MSXML. It must be written exactly as shown, on two lines.

The #import directive does more just than fulfill the general purpose of including information from a type library (similar to the way the #include directive brings in header files): It also creates so-called "smart pointer" interfaces for the COM interfaces defined in the type library being imported. Smart pointers are native C++ class wrappers that hide a lot of the messy details of creating and managing COM objects. One of the nicest things about them is that since they are native C++ classes, their destructors get called when the smart pointers go out of scope. Their destructors handle all the details of cleaning up the use of the COM object. Since they overload the indirection operator (->), we can use them just like any other pointer.

Smart pointers are particularly important to us because in MSXML's DOM implementation, all our DOM objects are accessed via pointers. We can reference a NodeList by using a regular pointer like this:

 IXMLDOMNodeList * pNodeList; 

or we can use the smart pointer approach like this:

 IXMLDOMNodeListPtr pNodeList; 

We use both types of pointers in the same way. The following code works with both declarations.

 while (pNodeList->item[iNodes] != NULL) 

However, the difference comes when we are finished using the interface. With dumb pointers, for our COM clients to be good citizens and help manage resources properly they must call the interface's AddRef and Release methods . With smart pointers this is done automatically.

The MSXML SDK code examples use both the dumb and smart pointer approaches. Following the KISS principle, I only use smart pointers. There may be cases in loops or in argument passing where this approach is not the most efficient, but again we're valuing simplicity over any miniscule effect on performance.

Note that I have adopted the convention of using an sp prefix with smart pointers.



Using XML with Legacy Business Applications
Using XML with Legacy Business Applications
ISBN: 0321154940
EAN: 2147483647
Year: 2003
Pages: 181

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net