Altova Mailing List Archives>Archive Index >microsoft.public.xml Archive Home >Recent entries >Thread Prev - CComPtr (MSXML in C++) [Thread Next] RE: CComPtr (MSXML in C++)To: NULL Date: 7/1/2005 1:01:00 PM > What is the difference (other than MSXML version) between:
>
> CComPtr<IXMLDOMDocument> spXMLDOM;
> HRESULT hr = spXMLDOM.CoCreateInstance(__uuidof(DOMDocument));
>
> and:
>
> IXMLDOMDocument2Ptr pXMLDoc = NULL;
> pXMLDoc.CreateInstance("Msxml2.DOMDocument.4.0");
There's not much difference. CComPtr is an ATL template for a smart pointer
(CComQIPtr is another one that can be extremely handy if you have to deal
with polymorphic or multi-interface components; it automatically performs a
QueryInterface for the pointer's coclass on any COM pointer you assign).
When I use the ATL pointers, I usually typedef some pointer types (e.g.
typedef CComPtr<IXMLDOMDocument> MyXMLDOMDocumentPtr) for any interface types
I'm using extensively, to make life easier.
The IXML... classes are similar smart pointers, based on the _com_ptr_t
class, when you #import the MSXML DLL. However, these are automatically
generated as typedefs for you. The #import will also generate "wrapper"
versions of all the class methods (unless you use raw_interfaces_only) that
automatically convert the HResult into a C++ exception and return the
appropriate result (no need to pass in variable references to get the return
result), and create VB-style properties (e.g. bstrXMLText = xNode->xml;
xNode2->text = bstrName;).
The core functionality of the CComPtr vs. _com_ptr_t smart pointer classes
is very similar, including reference counting, passthrough "->" access to
class members, etc., and you can create classes that inherit from a CComPtr
that implement the type of stuff that #import generates (although you'd have
to do it yourself for each interface).
> I like it because it have cleaner syntax than first example that I have been
> using. Take a look into this example:
>
> 1.
>
> CComPtr<IXMLDOMElement> nElem;
> hr = spXMLDOM->createElement(L"MyElem", &nElem);
> if (FAILED(hr)) throw "Unable to create element";
>
> 2.
>
> IXMLDOMElementPtr pTempNode = pXMLDoc->createElement(_T("MyElem"));
As I said, the only real difference is that the #import version is taking
care of the HResult handling in generated inline code. Nothing too fancy
(you can look at the code in the .tlh file).
> Do I have to free pTempNode?
No. Both CComPtr and _com_ptr_t perform an automatic release() if a
stack-based smart pointer goes out of scope, so you don't have to do it
manually. Both are also smart enough to set the pointer variable they wrap
to NULL if you release the pointer yourself, and provide Attach and Detach
methods if you have a need to wrap the pointer without touching the reference
counting.
Erik J Sawyer
CFT Programmer
Appro Systems
| ||||||
| Company | Legal | Press | Partners | Careers | Sitemap | Contact Us | Altova Blog | Mobile | Full Site | |||
|
