API: STL containers and Smart Pointers

Document created by 1-1S26RY on Feb 29, 2012Last modified by 1-1S26RY on Nov 2, 2012
Version 3Show Document
  • View in full screen mode

Working with COM interface pointers is made easier by using smart pointers, like ATL’s CComPtr<T> or the Visual Studio compiler generated _com_ptr_t<T>  specializations. These smart pointers typically overload the address-of operator operator&().

Many container classes, such as the STL container classes, expect to be able to obtain the addresses of their contained objects using the address-of operator.

The redefinition of 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.


Problems can be avoided by wrapping the container elements in a 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;




      #include <atlcomcli.h>


typedef std::vector<CAdapt<IModelDoc2Ptr> > AdaptedIModelDoc2Vector_t;


This can be used as follows:




AdaptedIModelDoc2Vector_t  vDocuments(lNumDocuments);


swApp->IGetDocuments(lNumDocuments, (IModelDoc2**)&vDocuments.front());


and iterated over like so:


for (AdaptedIModelDoc2Vector_t::iterator itr = vDocuments.begin();

itr != vDocuments.end(); itr++)


      IModelDoc2Ptr  swDocument(*itr);


_bstr_t  bstrTitle;




      // This doesn't compile as operator-> is not a member of

// CAdapt<T>.








The attached C++ add-in demonstrates this by shuffling stl::vector's containing unadapted and adapted smart pointers.

Load the add-in into SolidWorks, load an assembly with a few components, and select the two menu buttons to see each scenario, starting with the adapted scneario.

In the unadapted scenario, some or all vector elements will be NULL due to the address-of operator operator&() releasing the interface pointer when elements are swapped around.



The result will be that access violations will occur, crashing the application. So proceed with care ....




See also


SolidWorks API Help \ Getting Started \ Programming with the SolidWorks API \ STL Containers Classes and Smart Pointers

SolidWorks API Help \ Getting Started \ Programming with the SolidWorks API  \ Smart Pointers





CAdapt class



- Subscription Services required for full access.

- Looking for more API Examples?