How to use TComInterface properly?

故事扮演 提交于 2019-12-25 04:53:32

问题


I would like to use TComInterface to replace raw pointer.

My current code is:

{
TComInterface<IStoreNamespace> pStore;
if (SUCCEEDED(CoCreateInstance(CLSID_StoreNamespace, NULL, CLSCTX_INPROC_SERVER, IID_IStoreNamespace, (LPVOID*)&pStore)))
    {
    if (SUCCEEDED(pStore->Initialize(Form1->Handle, 1)))
        {
        //pStore->CallOtherMethods...
        }
    }
// Release()'d automatically?
}

If I understood correctly this overwrites the pStore pointer with new pointer so it doesn't call pStore->Release(); automatically from eventually previous instance using pStore.

Under what conditions is Release() called? I believe it may be when the variable goes out of scope even if I initialized it like this. And what is the proper way to initialize pStore in above example so it doesn't just overwrite pointer but also calls Release() first?


回答1:


TComInterface calls Release() on its internal interface when TComInterface goes out of scope and gets destructed. You can also call the TComInterface::Unbind() method if you want to manually Release() the interface sooner. TComInterface also calls Release() on its current interface if you assign a new interface pointer (or other TComInterface instance) via the = assignment operator.

TComInterface overrides the & operator to return a pointer to its internal interface, so you have to make sure that TComInterface is not holding an active interface before you call CoCreateInstance() (or anything else that will copy a new interface into TComInterface) or else the preview interface will be leaked and not released. TComInterface's default constructor sets the internal interface to NULL, so you don't usually have to worry about that, unless you re-use the same TComInterface variable multiple times, such as when using interface enumerators in a loop.



来源:https://stackoverflow.com/questions/20057281/how-to-use-tcominterface-properly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!