Skip to content

Make the CCoInitializer constructor exception safe #2675

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 4, 2021
Merged

Make the CCoInitializer constructor exception safe #2675

merged 2 commits into from
Jan 4, 2021

Conversation

isnullxbh
Copy link
Contributor

The source code example is accompanied by the following comment:

// An exception-safe wrapper class that manages the lifetime
// of the COM library in a given scope.

, but the CCoInitializer constructor throws an exception when the CoInitializeEx call completes with an error:

// Initialize the COM library on the current thread.
HRESULT hr = CoInitializeEx(NULL, dwCoInit);
if (FAILED(hr))
   throw hr;

I thought it may be a mistake in the comment, but the example below says otherwise:

int wmain()
{
   HRESULT hr;

   // Enable COM on this thread for the lifetime of the program.   
   CCoInitializer coinit(COINIT_MULTITHREADED);
   // Code
}

There is no try/catch block that encloses the creation of the CCoInitializer class instance.

The CCoInitializer implementation also indicates that the constructor shouldn't throw an exception:

explicit CCoInitializer(DWORD dwCoInit = COINIT_APARTMENTTHREADED)
   : _coinitialized(false)
{
   // Initialize the COM library on the current thread.
   HRESULT hr = CoInitializeEx(NULL, dwCoInit);
   if (FAILED(hr))
      throw hr;
   _coinitialized = true;
}

, otherwise, the usage of the _coinitialized flag is redundant - if an exception will be thrown at the constructor call, the destructor will never be called, so the _coinitialized flag will never be used.

Copy link
Contributor

@colin-home colin-home left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@isnullxbh
Thanks for the contribution. I think you're right about the intent with exceptions. I tweaked the edit a bit to cover the already-initialized case (which is almost certainly a sign the calling code has a bug, but keeps it from failing).

@colin-home colin-home merged commit 732e055 into MicrosoftDocs:master Jan 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants