首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >释放TStreamAdapter时指针操作无效

释放TStreamAdapter时指针操作无效
EN

Stack Overflow用户
提问于 2019-05-13 21:41:16
回答 1查看 84关注 0票数 1

有人能解释一下为什么我删除TStreamAdapter时会出现“指针操作无效”的问题吗?或者..。如何正确地从TStreamAdapter中释放内存?如果我删除了delete,它可以工作,但这会导致内存泄漏。即使我使用boost::scoped_ptr,它也会失败,并出现相同的错误。

注意:我也尝试过用soOwned值初始化TStreamAdapter,同样的错误。

代码:

代码语言:javascript
复制
HRESULT LoadFromStr(TWebBrowser* WB, const UnicodeString& HTML)
{
if (!WB->Document)
    {
    WB->Navigate("about:blank");
    while (!WB->Document) { Application->ProcessMessages(); }
    }

DelphiInterface<IHTMLDocument2> diDoc = WB->Document;

if (diDoc)
    {
    boost::scoped_ptr<TMemoryStream> ms(new TMemoryStream);

        {
        boost::scoped_ptr<TStringList> sl(new TStringList);
        sl->Text = HTML;
        sl->SaveToStream(ms.get(), TEncoding::Unicode);
        ms->Position = 0;
        }

    DelphiInterface<IPersistStreamInit> diPSI;

    if (SUCCEEDED(diDoc->QueryInterface(IID_IPersistStreamInit, (void**)&diPSI)) && diPSI)
        {
        TStreamAdapter* sa = new TStreamAdapter(ms.get(), soReference);
        diPSI->Load(*sa);
        delete sa;  // <-- invalid pointer operation here???

        // UPDATED (solution) - instead of the above!!!
        // DelphiInterface<IStream> sa(*(new TStreamAdapter(ms.get(), soReference)));
        // diPSI->Load(sa);
        // DelphiInterface is automatically freed on function end


        return S_OK;
        }
    }

return E_FAIL;
}

更新:我在这里找到了解决方案- http://www.cyberforum.ru/cpp-builder/thread743255.html

解决方案是使用_di_IStream sa(*(new TStreamAdapter(ms.get(), soReference)));或...DelphiInterface<IStream> sa(*(new TStreamAdapter(ms.get(), soReference)));

因为一旦IStream超出范围,它将自动释放它。至少它应该--这里有没有可能有内存泄漏?(CodeGuard没有检测到任何内存泄漏)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-14 04:46:31

TStreamAdapterTInterfacedObject的后代,它实现了引用计数语义。你根本不应该对它进行delete,当对象不再被任何人引用时,你需要让引用计数释放它。

使用_di_IStream (它只是DelphiInterface<IStream>的别名)是使用智能指针实现自动化的正确方法。TComInterface<IStream>CComPtr<IStream>也可以工作。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56113640

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档