0

I am using CComPtr to hold a pointer to a com object.

I also wrapped the resource with a class:

class ResourceWrapper {
public:
    ResourceWrapper()
    {

        CoInitializeEx(NULL, COINIT_MULTITHREADED);
        HRESULT hr = S_OK;
        if (FAILED( hr = CoCreateInstance(CLSID_Resource, NULL, CLSCTX_INPROC, IID_PPV_ARGS(&pResource)))||pResource==NULL)
        {

            throw std::runtime_error("failed to create instance");


        }

    }
    ~ResourceWrapper()
    {
        pResource =NULL;
        CoUninitialize();
    }
    CComPtr<IResource> Get()
    {
        return pResource;
    }
private:
    CComPtr<IResource> pResource;
    ResourceWrapper(const ResourceWrapper&);
    ResourceWrapper operator=(const ResourceWrapper&);


};

but then I thought that maybe CComPtr is implementing RAII and then the Wrapper I created is unnecessary.

I tried to google it, but I didn't understand if I need a wrapper or not.

SO my question is, if I use CComPtr, do I need to also create a wrapper?

user844541
  • 2,868
  • 5
  • 32
  • 60
  • 1
    `1` `~CComPtr` will release the pointer correctly without your wrapping it `2` `CoInitialize` there is generally not a good idea – Roman R. Aug 19 '13 at 12:41

1 Answers1

1

No, there is no need for your wrapper, and also, initialising and uninitialising COM like that is a really bad idea. Do it once at application startup and shutdown.

Mark Ingram
  • 71,849
  • 51
  • 176
  • 230
  • 1
    Indeed, while making a RAII version of CoInitialize/CoUninitialize is a good idea, putting them in the same class as a CComPtr is not. – Medinoc Aug 19 '13 at 13:09
  • 1
    Calling CoInitialize multiple times is completely fine. You just call CoUninitialise the correct number of times to reverse it. It's definitely counted (see the docs). If you play this game, remember to check the return value of CoInitialize and assert/fail fast if it didn't work: in particular, the first call is free to choose STA or MTA, but subsequent calls will barf if you try and change the model. – Nicholas Wilson Aug 19 '13 at 14:15
  • @NicholasWilson It's not that it's unsafe, it's just pointless. Especially in a pointer wrapper class! – Mark Ingram Aug 20 '13 at 08:16