C++ vector的delete与clear的区别 - 析构函数
1.clear() 不调用析构函数
2.delete *it 调用析构函数可用以下程序测试出来:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
ofstream txtout( "test.txt");
class A
{
public:
A()
{ txtout << "A constructor! " <<endl;
}
virtual ~A();
};
A::~A()
{ txtout << "A destructor! " <<endl;
}
const int test_size = 10;
int main()
{
{ vector < A* > the_vector,the_vector_copy;
A* pa;
for ( int i=0; i <test_size; i++ )
{ pa = new A();
the_vector.push_back(pa);
the_vector_copy.push_back(pa);
}
txtout <<endl;
txtout << "beforedelete... " <<endl;
pa = the_vector[0];
delete pa;
txtout << "afterdelete... " <<endl;
txtout <<endl;
txtout <<endl;
txtout << "beforeclear... " <<endl;
the_vector.clear();
txtout << "after clear..." <<endl;
txtout <<endl;
txtout <<endl;
txtout << "before alldeleting... " <<endl;
for ( int i=1; i <test_size; i++ )
delete the_vector_copy[i];
}
txtout << "after all deleting... " <<endl;
txtout <<endl;
}