BSTR 分配和释放内存

首先,可以用智能指针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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值