是否释放从记录集中返回的 BSTR

Release BSTR returned from recordset or not

这里有一些 ADODB 代码可以从记录集中检索 BSTR,但我不确定 BSTR 是否应该与 SysFreeString 一起发布。现在是这样,而且似乎很有效,但你应该自己做吗?

    BSTR bstr = m_pRecordset->Fields->GetItem ( field )->Value.bstrVal;

    int len = SysStringLen(bstr);

    while (len > 0 && iswspace(bstr[len-1])) len--;

    BSTR newstr = SysAllocStringLen(bstr, len);

    SysFreeString(bstr);
    SysFreeString(newstr);

您的代码有误。 m_pRecordset->Fields->GetItem ( field )->Value returns 一个 VARIANT 作为 _variant_t.

您应该将对象保存在一个临时变量中,访问数据,其余的由析构函数完成。

_variant_t val = m_pRecordset->Fields->GetItem ( field )->Value;

int len = SysStringLen(val.bstrVal);

while (len > 0 && iswspace(bstr[len-1])) len--;

BSTR newstr = SysAllocStringLen(val.bstrVal, len);
...
SysFreeString(newstr);

See sample here in the MSDN.

还应该提到的是,最好使用 CComBSTR_bstr_t 而不是 BSTR。