How does one return a local CComSafeArray to a LPSAFEARRAY output parameter?
I have a COM function that should return a SafeArray via a LPSAFEARRAY* out parameter. The function creates the SafeArray using ATL's CComSafeArray template class. My naive implementation uses CComSafeArray<T>::Detach() in order to move ownership from the local variable to the output parameter: void foo(LPSAFEARRAY* psa) { CComSafeArray<VARIANT> ret; ret.Add(CComVariant(42)); *psa = ret.Detach(); } int main() { CComSafeArray<VARIANT> sa; foo(sa.GetSafeArrayPtr()); std::cout << sa[0].lVal << std::endl; } The problem is that CComSafeArray::Detach() performs an Unlock operation so that when the