使用迭代器时崩溃 [英] Crash when used iterator
问题描述
我遇到了以下代码行的问题,它在删除时崩溃了。你能不能取悦代码让我知道这个问题
map :: iterator it = m_Map.begin();
while(it!= m_Map.end())
{
CTest * pDTerst(it-> second) );
if(pDTerst)
删除pDTerst; /崩溃了好几次
it ++;
}
m_Map.clear();
我尝试了什么:
我试过调试后发现问题在
CTest * pDTerst(it-> second);
if(pDTerst)
delete pDTerst; /崩溃有些时候
Iam having issue with the following line of code its crashing in delete. could you please the code and let me know the issue
map::iterator it = m_Map.begin();
while ( it != m_Map.end() )
{
CTest*pDTerst(it->second);
if ( pDTerst)
delete pDTerst; /crashing some times
it++;
}
m_Map.clear();
What I have tried:
I tried debugged and found the issue in the
CTest*pDTerst(it->second);
if ( pDTerst)
delete pDTerst; /crashing some times
推荐答案
你正在堆栈上创建一个CTest
实例并尝试将其删除。这当然会崩溃,因为你只能删除使用new
在堆上分配的对象。
所以你可能想做这样的事情(取决于第二个std :: pair
元素的类型):
You are creating aCTest
instance on the stack and trying to delete it aftwerwards. That will of course crash because you can only delete objects that has been allocated on the heap usingnew
.
So you would probably want to do something like this (depending on the type of the secondstd::pair
element):
delete it->second;
请注意,无需检查 NULL
因为 delete
允许传递它(什么都不做)。
Note that there is no need to check for NULL
because delete
allows passing it (does nothing).
这篇关于使用迭代器时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!