STL Container Classes and Smart Pointers
Working with COM interface pointers is made easier by using
smart pointers such as:
These smart pointers typically overload the address-of
operator operator&(). Many container classes, such as the STL
(Standard Template Library) container
classes, expect to be able to use the address-of operator to obtain the
addresses of their contained objects. Overloading the address-of operator can
cause compiler errors or have undesired side-effects at run-time, like asserts
or releasing interface pointers prematurely, leading to access violations later
on.
To avoid problems, wrap the container elements in the
templated helper class, CAdapt<T>, provided by ATL. CAdapt's primary role is to
hide the address-of operator redefinition.
For example, instead of defining:
typedef
std::vector<IModelDoc2Ptr> IModelDoc2Vector_t;
define:
#include
<atlcomcli.h>
typedef
std::vector<CAdapt<IModelDoc2Ptr> > AdaptedIModelDoc2Vector_t;
This can be
used as follows:
swApp->GetDocumentCount(&lNumDocuments);
AdaptedIModelDoc2Vector_t vDocuments(lNumDocuments);
swApp->IGetDocuments(lNumDocuments,
(IModelDoc2**)&vDocuments.front());
and
iterated like this:
for
(AdaptedIModelDoc2Vector_t::iterator itr = vDocuments.begin();
itr
!= vDocuments.end(); itr++)
{
IModelDoc2Ptr swDocument(*itr);
_bstr_t
bstrTitle;
swDocument->GetTitle(bstrTitle.GetAddress());
// This doesn't compile as operator->
is not a member of
// CAdapt<T>.
//(*itr)->GetTitle(bstrTitle.GetAddress());
(*itr).m_T->GetTitle(bstrTitle.GetAddress());
}
For more information about the CAdapt
class, see Microsoft article
CAdapt Class.