使用MSXML2::IXMLDOMDocument2Ptr每次都要CreateInstance和load(xmlfile)吗?

程序中需要多次对XML文件中数据进行查询,由于XML文件庞大,不能一次把全部数据select进内存, 这样就需要多次分批进行查询(对不同层次上的节点).

我遇到的问题是当把一个IXMLDOMDocument2Ptr的Instance放到静态变量里,似乎不起作用,这样就造成每次查询都要CreateInstance和load(xmlfile),当多线程进行读和写XML文件的时候,经常报访问冲突.

并且多次释放IXMLDOMDocument2Ptr的实例也会带来内存碎片吧?

到底问题出在哪?--访问冲突。

How to do?
---------------------------------------------------
2005-5-13 没办法,暂时每次都重新CreateInstance和load(xmlfile),这样是避免了访问冲突,但却在每次IXMLDOMDocument2Ptr->Release()的时候报错!

暂时不释放IXMLDOMDocument2Ptr, 却在使用IXMLDOMDocument2Ptr->save( _variant_t("test.xml") );的时候出来一个错:


what the hell is wrong?!

---------------------------------
16:18:01
终于发现是因为char * 被释放掉造成的Heap溢出, 奇怪怎么反而释放出更多的字符来了?一堆乱码。还是CString安全保险....

但最原始的问题还是没找到问题所在,即:每次都要实例化的,尝试了几个地方。好像还是因为指针被释放掉,再次使用必报空指针。

看来还是没能掌握好指针的"善始善终"的办法. 希望体会的高手指点指点.
---------------------------------
2005-5-14
终于找到了问题所在,原来是因为每次使用完,我使用IXMLDOMDocument2Ptr->Release() 的原因。实际上,只需要 IXMLDOMDocument2Ptr = NULL; 就可以了。 奇怪,那接口提供 Release() 干吗?

对于Release() 的解释是这样的:

IUnknown::Release

Decrements the reference count for the calling interface on a object. If the reference count on the object falls to 0, the object is freed from memory.
减少对一个object的引用次数,如果引用次数降到0,这个object将会从内存中释放.

ULONG Release(void);

Returns the resulting value of the reference count
返回引用次数. (英语怎么这么罗嗦?如果按字面,是否应该翻译成:返回引用次数的结果值,罗力八嗦)

If IUnknown::AddRef has been called on this object's interface n times and this is the n+1th call to IUnknown::Release,
这怎么理解?难道代码是这么写?
IUnknown::AddRef
IUnknown::Release();  //maybe here is manal
IUnknown::Release();   //and here is done by system?

super faint !

 the implementation of IUnknown::AddRef must cause the interface pointer to free itself.
接口AddRef的一个实现必须通过接口的指针去释放它(这个implementation )自己.

When the released pointer is the only existing reference to an object (whether the object supports single or multiple interfaces), the implementation must free the object.
当被释放掉的指针是正指向一个对象(无论这个对象是支持一个还是多个接口),这个实现必须释放指针所指的对象。

Call this function when you no longer need to use an interface pointer.
调用这个函数当你不再需要使用这个接口指针
If you are writing a function that takes an in-out parameter, call IUnknown::Release on the pointer you are passing in before copying the out-value on top of it.
如果你正写一函数,这函数需要输入输出参数,在拷贝输出值前,调用IUnknown::Release 释放你传入的这个指针。

代码是这么写:(i guess)

void functionName (object1 * p)
{
  ......
  IUnknown::Release();  //在给p赋值之前Release,而不是之后
                                     //上面说Release n+1次,可能是这里手工做一次
                                     //然后系统自动再做一次(垃圾回收?)
   p = ... ;
}

原文地址:https://www.cnblogs.com/babyblue/p/154430.html