Re: best way to "delete" all objects in a std::vector.
On Jun 4, 5:43 am, "Daniel T." <danie...@earthlink.net> wrote:
Daniel Pitts <newsgroup.spamfil...@virtualinfinity.net> wrote:
I have std::vector<Base *> bases;
I'd like to do something like:
std::for_each(bases.begin(), bases.end(), operator delete);
Is it possible without writing an adapter? Is there a better
way? Is there an existing adapter?
From Stroustrup's book.
struct Delete_ptr {
template<class T> T* operator()(T* p) const { delete p; return 0; }
};
...
transform(s.begin(),s.end(),s.begin(),Delete_ptr());
[To the original poster: ignore this: it is from an
obsessional nitpicker, only for expert nitpickers.]
Note that formally, the above still has undefined behavior,
since it leaves a deleted pointer in the container for a (very)
short time. The correct way of doing this would be:
struct Deleter
{
template< typename T >
void operator()( T*& p ) const
{
T* tmp = NULL ;
std::swap( p, tmp ) ;
delete tmp ;
}
} ;
...
std::for_each( s.begin(), s.end(), Deleter() ) ;
(Note that it even uses swap. Can't get much more in than
that.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34