title: Throwing C++ exceptions with CoInitialize and CoUninitialize
body: <p>I have a function like this:</p>
  
  <pre><code>bool op1();
  bool op2();
  
  bool foo() {
    CoInitialize(nullptr);
    if (!op1()) {
      CoUninitialize();
      return false;
    }
    // do more stuff, then call op2...
    if (!op2()) {
      CoUninitialize();
      return false;
    }
    // happy path
    CoUninitialize();
    return true;
  }
  </code></pre>
  
  <p>I want to refactor <code>foo()</code> to throw exceptions:</p>
  
  <pre><code>void foo() {
    CoInitialize(nullptr);
    if (!op1()) {
      CoUninitialize(); // I'm lazy, can't I automate this call?
      throw std::exception("Failed");
    }
    // ...
  </code></pre>
  
  <p>But I have to call <code>CoUninitialize()</code> each time I have an error.</p>
  
  <p>I thought about wrapping the COM init calls inside a class, so the destructor <a href="https://stackoverflow.com/q/8311457/6923555">will do the cleanup</a>, but having an unused object feels strange to my eyes:</p>
  
  <pre><code>class comlib {
  public:
    comlib() { CoInitialize(nullptr); }
    ~comlib() { CoUninitialize(); } // automated!
  };
  
  void foo() {
    comlib nobodyEverCallsMe;
    if (!op1()) {
      throw std::exception("Failed");
    }
    // ...
  </code></pre>
  
  <p>Is there a better approach to this?</p>