[C/C++] オブジェクトのnew/deleteにともなうvectorへの自動追加/削除
#include <iostream> #include <vector> #include <algorithm> using namespace std; class A; class A_cmp { public: A_cmp(A *a) { this->a = a; } bool operator()(A *obj) const { return obj == a; } A *a; }; class A { public: A(int n) { cout << "created " << this << " " << n << endl; this->n = n; v.push_back(this); } ~A() { cout << "deleted " << this << " " << n << endl; A::v.erase(remove_if(A::v.begin(), A::v.end(), A_cmp(this)), A::v.end()); } int n; static vector<A *> v; }; vector<A *> A::v; int main() { A *a0 = new A(0); A *a1 = new A(1); A *a2 = new A(2); A *a3 = new A(3); A *a4 = new A(1); delete a1; delete a3; cout << "list up all items in v" << endl; vector<A *>::iterator it = A::v.begin(); while (it != A::v.end()) { cout << *it << " " << (*it)->n << endl; it++; } return 0; }
という感じにしてあげると、オブジェクトをnew/deleteしたときに適当なvectorへの追加/削除を自動的に行うことができます。実行結果は下記のようになります。
created 0x7c1010 0 created 0x7c1040 1 created 0x7c1030 2 created 0x7c1050 3 created 0x7c1078 1 deleted 0x7c1040 1 deleted 0x7c1050 3 list up all items in v 0x7c1010 0 0x7c1030 2 0x7c1078 1