Re: best way to "delete" all objects in a std::vector.
On Jun 4, 6:08 pm, "jason.cipri...@gmail.com"
<jason.cipri...@gmail.com> wrote:
On Jun 4, 7:25 am, James Kanze <james.ka...@gmail.com> wrote:
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:
What has undefined behavior? If you are talking about the
transform over all, or the () operator, neither are undefined.
It is well- defined that it leaves an invalid pointer in the
container for a very short time. What's undefined is if
something attempts to dereference that pointer during that
time.
A pointer, after delete, may not even be read or copied (since
one of the effects of delete could be to render its value
"trapping"). Which means that it is not Copiable, and thus,
you've violated the requirements of the standard containers.
In practice, of course, there are very, very few implementations
where it might actually trap: to do so means 1) that the
hardware can trap on such pointers (Intels IA-32 is the only one
I know of where this might currently be a problem), 2) that the
library actually does free the memory in a way that unmaps it
(none that I know of do---they all keep the memory mapped to the
process for potential future use), 3) that the compiler actually
does the copy in such a way that might trap (I think some Intel
compilers do), and 4) that std::vector actually does try to copy
it. That last point is, of course, the ultimate guarantee;
std::vector will normally only copy anything if you try to
increase the size of the vector.
But the standard still says that all of the elements must be
copiable, even if there's no earthly reason for the vector to
copy.
--
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