3

Due to code refactoring a class that is part of some library interface now uses COM internally. This means that CoInitialize / CoUninitialize needs to be called now on any thread which wants to use my library class.

To allow library users a smooth transition towards the new version I plan to add the call to CoInitialize to the class constructor and CoUninitialize to the class destructor. Will this add some significant runtime overhead, assuming that the class is instantiated 1-2 times per second?

blerontin
  • 2,892
  • 5
  • 34
  • 60
  • 13
    That's the wrong solution. It's never the job of a class to initialize COM. That job falls to the creator of the thread. Place a requirement that any thread that uses your class has correctly initialized COM. – David Heffernan Aug 21 '19 at 13:21
  • As there is quite some code using my library outside of my reach: Is there a way to communicate that requirement besides documentation (e.g. by compiler checks)? – blerontin Aug 21 '19 at 13:30
  • Certainly can't be done by the compiler because you don't control compilation of your host code. It's fine to communicate the requirement by documentation. In fact that is best practise. If course plenty of your users won't read the documentation but that's not a new problem for you I am quite sure!! – David Heffernan Aug 21 '19 at 13:32
  • I Agree with David, See Hans Passant's answer [here](https://stackoverflow.com/a/7824727/800214) – whosrdaddy Aug 21 '19 at 14:41
  • Maybe it is the job of the thread creator to initialize COM, even though I would welcome some reasoning for that rule. But I really don't like to introduce runtime errors due to library updates. Besides the aesthetic argument, is there some significant CPU/memory overhead in calling COM (un-)initialization multiple times? – blerontin Aug 21 '19 at 14:53
  • 1
    And yet another almost duplicate: https://stackoverflow.com/questions/9286600/when-do-i-need-to-call-coinitialize-in-this-scenario – Jerry Dodge Aug 21 '19 at 18:18
  • Linked questions answer whether multiple callis to CoInitialize/CoUninitialize are ok. They are not duplicates since they've got nothing to do with the overhead of initializing/finalizing COM or attempting to do so. I don't think, though, this question can realistically be answered unless someone knows how this is implemented internally. – Sertac Akyuz Aug 22 '19 at 09:31
  • 1
    @SertacAkyuz: yeah it's not an exact dupe, but the takeaway point is that it is the responsibility of the caller to do the COM initialization, not the library. From that POV, this question is moot. – whosrdaddy Aug 23 '19 at 07:55

0 Answers0