#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
static long g_g = 0, g_x = 0;
typedef struct tagMy
{
int i;
char sz[32];
tagMy()
{
cout << " 构造 " << g_g++ << endl;
memset(this, sizeof(tagMy), 0);
}
~tagMy()
{
cout << " 析构 " << g_x++ << endl;
}
}MY, *PMY;
typedef vector<MY> vecMy;
typedef vecMy::iterator iterMy;
typedef vector<PMY> vecPMy;
typedef vecPMy::iterator iterPMy;
vecMy _vecMy;
vecPMy _vecPMy;
PMY A()
{
MY *pMy = new MY();
if (pMy)
{
pMy->i=1;
strcpy_s(pMy->sz, sizeof(char)*32, "Hello");
} // end if
return pMy;
}
void B(int nTimes)
{
PMY pMy = A();
if ( pMy )
{
// 此处,将根据_vecMy size的大小调用size次析构函数
cout << " _vecMy size " << _vecMy.size() << endl;
_vecMy.push_back(*pMy);
cout << " delete 调用析构函数" << endl;
delete pMy;
pMy = NULL;
} // end if
cout << " ------------------- 第" << nTimes + 1 << "次" << endl ;
}
void C(int nTimes)
{
PMY pMy = A();
if ( pMy )
{
// 此处,将不会根据_vecMy size的大小调用析构函数
cout << " _vecMy size " << _vecMy.size() << endl;
_vecPMy.push_back(pMy);
} // end if
cout << " ------------------- 第" << nTimes + 1 << "次" << endl ;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << " B 函数 " << endl;
for ( int i = 0; i < 10; i++ )
B(i);
cout << " C 函数 " << endl;
for ( int i = 0; i < 10; i++ )
C(i);
iterPMy iter = _vecPMy.begin();
for ( ; iter != _vecPMy.end(); iter++ )
{
delete *iter;
*iter = NULL;
} // end for
system("pause");
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
static long g_g = 0, g_x = 0;
typedef struct tagMy
{
int i;
char sz[32];
tagMy()
{
cout << " 构造 " << g_g++ << endl;
memset(this, sizeof(tagMy), 0);
}
~tagMy()
{
cout << " 析构 " << g_x++ << endl;
}
}MY, *PMY;
typedef vector<MY> vecMy;
typedef vecMy::iterator iterMy;
typedef vector<PMY> vecPMy;
typedef vecPMy::iterator iterPMy;
vecMy _vecMy;
vecPMy _vecPMy;
PMY A()
{
MY *pMy = new MY();
if (pMy)
{
pMy->i=1;
strcpy_s(pMy->sz, sizeof(char)*32, "Hello");
} // end if
return pMy;
}
void B(int nTimes)
{
PMY pMy = A();
if ( pMy )
{
// 此处,将根据_vecMy size的大小调用size次析构函数
cout << " _vecMy size " << _vecMy.size() << endl;
_vecMy.push_back(*pMy);
cout << " delete 调用析构函数" << endl;
delete pMy;
pMy = NULL;
} // end if
cout << " ------------------- 第" << nTimes + 1 << "次" << endl ;
}
void C(int nTimes)
{
PMY pMy = A();
if ( pMy )
{
// 此处,将不会根据_vecMy size的大小调用析构函数
cout << " _vecMy size " << _vecMy.size() << endl;
_vecPMy.push_back(pMy);
} // end if
cout << " ------------------- 第" << nTimes + 1 << "次" << endl ;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << " B 函数 " << endl;
for ( int i = 0; i < 10; i++ )
B(i);
cout << " C 函数 " << endl;
for ( int i = 0; i < 10; i++ )
C(i);
iterPMy iter = _vecPMy.begin();
for ( ; iter != _vecPMy.end(); iter++ )
{
delete *iter;
*iter = NULL;
} // end for
system("pause");
return 0;
}
为什么在 _vecMy.push_back(*pMy); 的时候会调用~tagMy()析构函数呢?而且根据_vecMy.size的大小调用相应的次数, 而运行 _vecPMy.push_back(pMy);时,又不会调用析构函数呢?