简体   繁体   中英

Is this a good way to manage initializations of COM?

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?

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;
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM