释放 TStreamAdapter 时指针操作无效

Cod*_*345 1 com c++builder

谁能澄清为什么当我尝试删除时会收到“无效的指针操作” TStreamAdapter?或者...如何正确释放内存TStreamAdapter?如果我删除它,它会起作用,delete但这会导致内存泄漏。即使我使用 boost::scoped_ptr 它也会失败并出现相同的错误。

注意:我也尝试TStreamAdaptersoOwned值初始化,同样的错误。

代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

更新:我在这里找到了解决方案 - 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 没有检测到任何内存泄漏)。

Rem*_*eau 5

TStreamAdapter是一个TInterfacedObject后代,它实现了引用计数语义。你根本不应该delete这样做,当它不再被任何人引用时,你需要让引用计数释放该对象。

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