Search code examples
c++comconstructorinitialization-list

Anyway to call CoInitialize() before an initialization list?


Here is my C++ code of a constructor of ThorDetectorSwitch.cpp file:

ThorDetectorSwitch::ThorDetectorSwitch() : _mcSwitch(__uuidof(MCLControlClass))
{
    _A  = WstringToBSTR(L"A"); 
    _B  = WstringToBSTR(L"B");
    _C  = WstringToBSTR(L"C");
    _D  = WstringToBSTR(L"D");

    _deviceDetected = FALSE;
}

As you can see, an initialization list, _mcSwitch(__uuidof(MCLControlClass)), is used to initialize a COM object (MCLControlClass, which is registered from a COM dll).

I am wondering is there anyway I can call CoInitialize() before this initialization list? Because I am getting exceptions of "CoInitialize() has not been called". Or any other way to avoid this exception?

Thanks a lot.


Solution

  • First I recommend you use CoInitializeEx instead of CoInitialize. Even the MSDN documentation recommends this. Second I recommend that you call CoInitializeEx in main() and at the start of each additional thread that requires the use of COM objects. There are very good reasons for this. For instance each call to CoInitializeEx should have a corresponding call to CoUninitialize before the thread ends. This ensures the COM library is properly terminated. If you call it from the constructor you also have to manage the number of times the COM library is initialized so the right number of calls to CoUninitialize are made. Another issue is when subsequent calls are made to CoInitializeEx with a different apartment model it will fail. If this happens and your constructor is checking for errors like it should you end up with a failure condition during instantiation. How do you handle an error condition like that in a constructor? By throwing an exception - not a very pleasant thing to have happen.

    My final recommendation is to read the documentation and do things the right way otherwise you end up scratching your head like have been for the last few days.