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