问题描述
我想使用TComInterface替换原始指针。
I would like to use TComInterface to replace raw pointer.
我当前的代码是:
{
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?
}
如果我理解正确,这会用新的指针覆盖pStore指针,因此它不会t使用 pStore
从最终的先前实例中自动调用 pStore-> Release();
。
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
.
在什么条件下调用 Release()
?我相信即使我这样初始化变量,也可能是变量超出范围的时候。在上面的示例中初始化pStore的正确方法是什么,这样它不仅覆盖指针,而且还首先调用 Release()
?
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?
推荐答案
TComInterface
在其内部调用 Release()
TComInterface
超出范围并被破坏时的界面。如果要更快地手动 Release()
接口,也可以调用 TComInterface :: Unbind()
方法。如果分配了新的接口指针(或其他<$ c $,则 TComInterface
还将在其当前接口上调用 Release()
) c> TComInterface 实例)通过 =
赋值运算符。
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
会覆盖&
运算符,以返回指向其内部接口的指针,因此必须确保 TComInterface
在调用 CoCreateInstance()
之前没有保持活动接口(或将新接口复制到的其他任何方法) TComInterface
),否则预览界面将被泄漏而不被释放。 TComInterface
的默认构造函数将内部接口设置为NULL,因此通常不必担心,除非您重复使用相同的 TComInterface
变量多次,例如在循环中使用接口枚举器时。
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.
这篇关于如何正确使用TComInterface?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!