views:

47

answers:

1

Hello everyone :)

I'm very new to anything involving Component Object Model, and I'm wondering if this method of managing calls to CoInitalize/CoUninitalize makes sense:

COM.hpp:

#pragma once

namespace WindowsAPI { namespace ComponentObjectModel {

class COM
{
    COM();
    ~COM();
public:
    static void Setup();
};

}}

COM.cpp:

#include <Windows.h>
#include "COM.hpp"

namespace WindowsAPI { namespace ComponentObjectModel {

COM::COM()
{
    if (CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) != S_OK) throw std::runtime_error("Couldn't start COM!");
}

COM::~COM()
{
    CoUninitialize();
}

void COM::Setup()
{
    static COM instance;
}

}}

Then any component that needs COM just calls COM::Setup() and forgets about it.

Does this make sense or am I breaking any "rules" of COM?

+1  A: 

I don't believe that static storage variables are destroyed on dll unload, but you shouldn't be using this from a dll anyway.

I generally do something similar, but I don't bother with a function static, I just make the ctor/dtor public and drop an instance in my main():

int WINAPI wWinMain(...) {
    Com::ComInit comInitGuard;
    ...
Simon Buchan
This is a static library(therefore statics are destroyed when the application terminates) which doesn't have access to WinMain. The "static variable" is just the standard C++ singleton pattern.
Billy ONeal
This seems alright then, although I'm wary of destructors on statics, since you have little control over ordering. Don't depend on other static destructors, for say singleton COM objects, running before or after it.
Simon Buchan
Starting a thread in a DLL is common enough. So is wanting to select MTA.
Hans Passant
I don't know what the relevance of starting a thread is, but you cannot start a thread, load a library, or do anything else interesting in DllMain, which is when statics would be created/destroyed.
Simon Buchan