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 << "before delete... " <<endl;

      pa = the_vector[0];

      delete pa;

      txtout << "after delete... " <<endl;

      txtout <<endl;

 

      txtout <<endl;

      txtout << "before clear... " <<endl;

      the_vector.clear();

      txtout << "after clear... " <<endl;

      txtout <<endl;

 

      txtout <<endl;

      txtout << "before all deleting... " <<endl;

      for (  int i=1; i <test_size; i++ )

         delete the_vector_copy[i];

   }

   txtout << "after all deleting... " <<endl;

   txtout <<endl;

}


 code::blocks运行结果:

Aconstructor! 
Aconstructor! 
Aconstructor! 
Aconstructor! 
Aconstructor! 
Aconstructor! 
Aconstructor! 
Aconstructor! 
Aconstructor! 
Aconstructor! 

beforedelete... 
Adestructor! 
afterdelete... 


beforeclear... 
afterclear... 


before alldeleting... 
Adestructor! 
Adestructor! 
Adestructor! 
Adestructor! 
Adestructor! 
Adestructor! 
Adestructor! 
Adestructor! 
Adestructor! 
after alldeleting... 

你可能感兴趣的:(C++,vector,测试,delete,Constructor,destructor)