listじゃなくてvectorだけど。
#include <iostream> #include <vector> using namespace std; class Hoge { public: int number; virtual ~Hoge(){ cout << number << endl; } typedef vector<Hoge*> List; typedef vector<Hoge*>::iterator Iterator; }; class Piyo : public Hoge { public: Piyo(int a){ number=a; cout << number << endl; } }; int main() { // とりあえず空のリストを作る Hoge::List hogelist; cout << "A:" << hogelist.size() << endl; // newして足していく hogelist.push_back( new Piyo(10) ); hogelist.push_back( new Piyo(20) ); hogelist.push_back( new Piyo(30) ); cout << "B:" << hogelist.size() << endl; // 全deleteする // for( unsigned int i=0; i<hogelist.size(); i++ ) delete hogelist[i]; // ←動くけど格好悪い for( Hoge::Iterator it = hogelist.begin(); it!=hogelist.end(); ++it ) delete (*it); cout << "C:" << hogelist.size() << endl; // 要素全消しする(一応) hogelist.clear(); cout << "D:" << hogelist.size() << endl; return 0; }
$ ./a.out A:0 10 20 30 B:3 10 20 30 C:3 D:0