最近在玩 MSHTML 和 MSXML,被一堆 COM 接口搞的晕头转向。
以前也玩过一些,但基本都是照抄别人的代码,也没注意到 IDispatch * 和 IDispatchPtr 有啥区别,就模糊的认为可能是同一个东东的两种写法罢……
这次趁机仔细研究了一番,转载3篇 COM 智能指针的详细的介绍,以备不时之需
ATL智能指针类
ATL中包含的智能指针包括:CAutoPtr、CAutoPtrArray和CAutoPtrList, CComPtr和CComQIPtr
一、CAutoPtr、CAutoPtrArray和CAutoPtrList
CAutoPtr是普通智能指针类,CAutoPtrArray是智能指针数组,两者都在atlbase.h中声明;CAutoPtrList是智能指针列表,在atlcoll.h中声明。
二、CComPtr和CComQIPtr
CComPtr和CComQIPtr都是用来管理COM接口指针的类,CComQIPtr可完全取代CComPtr,两者的区别在于:CComQIPtr实现了运算符的重载功能,它可以自动调用QueryInterface()函数,CComQIPtr 唯一的缺点是不能定义 IUnknown * 指针。CComQIPtr<IUnknown > spUn是错误的。
1.声明和定义:
声明和定义一个CComQIPtr指针ISample。
CComQIPtr<ISample> spSample(IOtherInterface); 等价于
CComQIPtr<ISample> spSample =IOtherInterface;/*运算符重载*/ 等价于
CComQIPtr<ISample> spSample;
IOtherInterface->QueryInterface(IID_ISample, &spSample);
2.函数调用:
智能指针调用函数分智能指针函数调用和智能指针内部接口指针函数调用,如上面声明的spSample,
spSample.CoCreateInstance(),spSample.QueryInterface等价于API函数调用::CoCreateInstance()和::QueryInterface();
spSample.QueryIn