有人能解释一下为什么我删除TStreamAdapter时会出现“指针操作无效”的问题吗?或者..。如何正确地从TStreamAdapter中释放内存?如果我删除了delete,它可以工作,但这会导致内存泄漏。即使我使用boost::scoped_ptr,它也会失败,并出现相同的错误。
注意:我也尝试过用soOwned值初始化TStreamAdapter,同样的错误。
代码:
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没有检测到任何内存泄漏)。
发布于 2019-05-14 04:46:31
TStreamAdapter是TInterfacedObject的后代,它实现了引用计数语义。你根本不应该对它进行delete,当对象不再被任何人引用时,你需要让引用计数释放它。
使用_di_IStream (它只是DelphiInterface<IStream>的别名)是使用智能指针实现自动化的正确方法。TComInterface<IStream>和CComPtr<IStream>也可以工作。
https://stackoverflow.com/questions/56113640
复制相似问题