使用_bstr_t在函数中传递BSTR *类型的参数

这样做的正确方法是什么:
_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);
谢谢     
已邀请:
BSTR是引用计数,我严重怀疑如果你使用GetAddress()将会正常工作。可悲的是,源代码无法进行仔细检查。我总是这样做:
BSTR temp = 0;
HRESULT hr = p->GetDescription(&temp);
if (SUCCEEDED(hr)) {
    _bstr_t wrap(temp, FALSE);
    // etc..
}
    
要跟进@Hans的答案 - 构建
_bstr_t
的适当方法取决于
GetDescription
是否会返回你拥有的
BSTR
,或者引用你不必释放的内存。 这里的目标是最小化副本数量,但也避免在返回的数据上手动调用
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..
}
    
迟到的答案可能不适用于Visual Studio的早期(或更高版本)版本;然而, VS 12.0具有内联的
_bstr_t
实现,显然,当在处女
_bstr_t
上调用
GetBSTR()
时,内部
Data_t
实例创建的
m_RefCount
为1。所以你的第一个例子中的
_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);
此评估基于VS 12.0的
comutil.h
。     

要回复问题请先登录注册