When using remove or erase to delete elements when saving the pointer type of the class in vector, it is necessary to prevent memory leakage. Generally, elements stored in the vector are manually new objects. These objects must be manually destroyed to prevent memory leakage.
The remove or erase of vector only clears the pointer from the vector, and copies the remaining elements to generate a new vector object, which is not responsible for clearing the object itself. Therefore, delete is required.
If the pointer type is a base class, define a virtual destructor for the base class.
# Include <iostream>
# Include <vector>
# Include <Yut/string. h>
Class ...{
Public:
A (int A): A ()...{}
Virtual ::~ A ()...{
Cerr <"222" <Endl;
}
Int;
};
Vector <A * >:: iterator get (vector <A *> & SS, int key )...{
Vector <A * >:: iterator it = ss. Begin ();
Cerr <"key:" <key <Endl;
Cerr <"SS size:" <ss. Size () <Endl;
While (it! = Ss. End ())...{
Cerr <"(* It)-> A:" <(* It)-> A <Endl;
If (* It)-> A = Key )...{
Return it;
}
It ++;
}
Return ss. End ();
}
Void main ()...{
Vector <A *> a_p;
Int idx = 10;
While (idx> 0 )...{
A * P = new A (idx );
A_p.push_back (P );
Idx --;
}
Int key = 3;
Vector <A *>: iterator it = get (a_p, 3 );
If (it! = A_p.end ())...{
Delete * it;
A_p.erase (it );
} Else ...{
Cerr <"not found" <Endl;
}
}