简要说下使用vector和指针的指针保存和删除。
第一种使用vector:
1.定义一个结构:
struct TestPoint
{
CString strPoint;
int iPoint;
BOOL bPoint;
TestPoint()
{
strPoint = _T("");
iPoint = 0;
bPoint = FALSE;
}
};
使用std::vector<TestPoint*> m_TestPointVec 保存
2.定义两个函数
//分配内存
void Init()
{
TestPoint *pTest = NULL;
CString strTest;
for (int i=0; i< 10; i++)
{
pTest = new TestPoint;
if (i % 2 == 0)
{
pTest->bPoint = TRUE;
}
else
{
pTest->bPoint = FALSE;
}
pTest->iPoint = i+ 1;
strTest.Format(_T("%d"), i);
pTest->strPoint =_T("Test point: ") + strTest;
m_TestPointVec.push_back(pTest);
}
}
//释放内存
void Destroy()
{
try
{
TestPoint *pTest = NULL;
std::vector<TestPoint*>::iterator citer = m_TestPointVec.begin();
for (citer; citer != m_TestPointVec.end(); citer++)
{
pTest = (*citer);
delete pTest;
}
m_TestPointVec.clear();
}
catch (...)
{
MessageBox(_T("Error: Destroy()"));
}
}
第二种使用指针的指针:
1.定义一个结构:
struct TestPoint
{
CString strPoint;
int iPoint;
BOOL bPoint;
TestPoint()
{
strPoint = _T("");
iPoint = 0;
bPoint = FALSE;
}
};
2.定义两个函数
//分配内存
void Init()
{
m_pTestVect = new TestPoint*[10];
memset(m_pTestVect, 0, sizeof(TestPoint*)*10);
CString strTest;
for (int i=0; i< 10; i++)
{
m_pTestVect[i] = new TestPoint;
if (i % 2 == 0)
{
m_pTestVect[i]->bPoint= TRUE;
}
else
{
m_pTestVect[i]->bPoint = FALSE;
}
m_pTestVect[i]->iPoint = i+ 1;
strTest.Format(_T("%d"), i);
m_pTestVect[i]->strPoint =_T("Test point: ") + strTest;
}
}
//释放内存
void Destroy()
{
if (m_pTestVect)
{
for (int i=0; i<10; i++)
{
if (m_pTestVect[i])
{
try
{
delete m_pTestVect[i];
}
catch(...)
{
MessageBox(_T("Error:ClearSrcList()"));
}
}
}
try
{
delete []m_pTestVect;
}
catch(...)
{
MessageBox(_T("Error:ClearSrcList()"));
}
m_pTestVect = NULL;
}
}
分配对象也是一样。
总结:m_TestPointVec.clear()和 m_pTestVect = NULL 比较容易忽略。