执行此操作的正确方法是:
_bstr_t description;
errorInfo->GetDescription( &description.GetBSTR() );或者:
_bstr_t description;
errorInfo->GetDescription( description.GetAddress() );其中,IError:GetDescription定义为:
HRESULT GetDescription (BSTR *pbstrDescription);我知道我可以轻松做到这一点:
BSTR description= SysAllocString (L"Whateva"));
errorInfo->GetDescription (&description);
SysFreeString (description);谢谢
发布于 2010-12-03 23:39:45
BSTR是引用计数的,如果你使用GetAddress(),我严重怀疑它是否能正常工作。遗憾的是,源代码不能用于复核。我一直是这样做的:
BSTR temp = 0;
HRESULT hr = p->GetDescription(&temp);
if (SUCCEEDED(hr)) {
_bstr_t wrap(temp, FALSE);
// etc..
}发布于 2010-12-04 00:41:43
继续@Hans的回答-构造_bstr_t的适当方式取决于GetDescription是返回您自己的BSTR,还是返回引用了您不必释放的内存的up。
这里的目标是最小化副本的数量,但也要避免对返回的数据进行任何手动调用SysFreeString。我将按如下所示修改代码,以澄清这一点:
BSTR temp = 0;
HRESULT hr = p->GetDescription(&temp);
if (SUCCEEDED(hr)) {
_bstr_t wrap(temp, false); // do not copy returned BSTR, which
// will be freed when wrap goes out of scope.
// Use true if you want a copy.
// etc..
}发布于 2016-07-19 12:38:28
迟来的回答可能不适用于Visual Studio的早期(或更高)版本;然而,VS 12.0具有内联的_bstr_t实现,并且很明显,当在原始_bstr_t上调用GetBSTR()时,将使用m_RefCount 1创建内部Data_t实例。因此,第一个示例中的_bstr_t生命周期看起来没问题:
_bstr_t description;
errorInfo->GetDescription( &description.GetBSTR() );但是如果_bstr_t是脏的,现有的内部m_wstr指针将被覆盖,从而泄漏它引用的前一个内存。
通过使用以下operator&,可以使用脏_bstr_t,因为它首先是通过Assign(nullptr)清除的。重载还提供了使用地址运算符而不是GetBSTR()的便利;
BSTR *operator&(_bstr_t &b) {
b.Assign(nullptr);
return &b.GetBSTR();
}因此,您的第一个示例可能如下所示:
_bstr_t description(L"naughty");
errorInfo->GetDescription(&description);该评估基于VS12.0中的comutil.h。
https://stackoverflow.com/questions/4346828
复制相似问题