我的回答也晚了。假设你有签名HRESULT PutDescription (BSTR NewDescription);
。在这种情况下,请执行以下操作
_bstr_t NewAdvice = L"Great advice!";
HRESULT hr1 = PutDescription(NewAdvice.GetBSTR());
根据 COM 的规则,该函数PutDescription
不允许更改甚至破坏传递的BSTR
.
相反,通过函数HRESULT GetDescription (BSTR *pActualDescription);
传递处女:_bstr_t
GetAddress()
_bstr_t GetAdvice;
HRESULT hr2 = GetDescription(GetAdvice.GetAddress());
该函数GetAddress()
释放任何现有字符串并返回新分配的字符串的地址。所以,如果你传递一个_bstr_t
有一些内容的,这个内容将被释放并因此丢失。所有_bstr_t
共享相同的 s 都会发生同样的情况BSTR
。但我认为这是一件愚蠢的事情。为什么将带有内容的参数传递给应该更改该内容的函数?
_bstr_t GetAdvice = L"This content will not survive the next function call!";
HRESULT hr = GetDescription(GetAdvice.GetAddress());
一个真正的白痴甚至可能会传递一个_bstr_t
分配给 raw 的 a BSTR
:
BSTR Bst = ::SysAllocString(L"Who would do that?");
_bstr_t GetDescr;
GetDescr.Attach(Bst);//GetDescr wraps Bst, no copying!
HRESULT hr = GetDescription(GetDescr.GetAddress());
在这种情况下,GetDescr
得到预期值,但内容Bst
是不可预测的。