首先,可以用智能指针CComBSTR, 它会在它的作用域消失之后调用析构函数,把m_str通过sysfreestring释放了,以下是CComBSTR源代码
CComBSTR(_In_opt_z_ LPCOLESTR pSrc)
{
if (pSrc == NULL)
{
m_str = NULL;
}
else
{
m_str = ::SysAllocString(pSrc);
if (!*this)
{
AtlThrow(E_OUTOFMEMORY);
}
}
}
inline CComBSTR::~CComBSTR() throw()
{
::SysFreeString(m_str);
}
Here is a good example1, will call ~CComBST at the end of main
int main() {
CComBSTR temp = CComBSTR(L"execute ~CComBSTR at the end of main");
BSTR bstrValSuccess1 = temp;
}
example2 is almost the same as what example1 CComBST do. If you return code just in one line, you can choose sysfreestring by yourself, but if you return code in lots of line, you have to add sysfreestring to every where called return. It is a little ugly.
int main() {
BSTR bstrValSuccess2 = SysAllocString(L"need release yourself");
SysFreeString(bstrValSuccess2);
}
Attention, Don't write like that:
BSTR bstrValError = CComBSTR(L"execute ~CComBSTR after that line");
这种作用域在这行之后就直接结束导致调用析构的行径。
May be you will argue, bstrValError still has right value, then I suggest you search "a dangling pointer after assignment". The memoryis free, it means every things may happen to there. It happens to work, to it will be garbage character.