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;
typedef std::vector<CAdapt<IModelDoc2Ptr> > AdaptedIModelDoc2Vector_t;
This can be used as follows:
and iterated over like so:
for (AdaptedIModelDoc2Vector_t::iterator itr = vDocuments.begin();
itr != vDocuments.end(); itr++)
// This doesn't compile as operator-> is not a member of
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 ....
|- required for full access.|
- Looking for more API Examples?