I have an ATL COM component method which takes a BSTR as an in parameter. I need to add each call to this method in an array. I can’t use a SAFEARRAY as that is fixed size so I was thinking that std::vector would be the easiest choice. Of course I will need to call SysAllocString for each addition to the vector. This means that SysFreeString needs to be called for each entry before the vector is destroyed.
I was looking for an easier/cleaner solution and thought of declaring the vector as vector<_bstr_t> which would include automatic cleanup. However, something in the back of my mind is raising the alarm at holding what is effectively a smart pointer in a standard container. Are my worries justified or can I safely do this? If not are there any other nicer solutions?
Yes. While you can safely use
_bstr_tbear in mind that not only is it a smart pointer, but it is a reference counted smart pointer. Which means additional cost.I would typically use a
CComBSTRinstead ofBSTRor_bstr_t. If you need reference counting then you have to fall back on_bstr_t. E.g: If you’re also using ATL, you will probably only ever wantCComBSTRs.So, before making a choice do consider the following:
_bstr_tis a reference counted smart-pointer wrapper overBSTRwhereasCComBSTRdoes not provide any reference counting._bstr_tdoes not redefine the address-of operator and can thus be safely stored in a STL container. WithCComBSTRyou will need to useCAdapt.About the
CAdaptobject:And then you can use: