Topic: Passing forward iterator as parameter


Author: mddibern@cs.ubc.ca (Michael Domenic DiBernardo)
Date: Wed, 10 Jan 2007 23:34:44 GMT
Raw View
How might I declare a function that takes a forward_iterator as a
parameter? I want a generic function that will iterate over a given
forward iterator and free all of the pointers contained therein.

The gist:

#include <iterator>

void deleteAll(std::forward_iterator begin, std::forward_iterator end) {
   while (begin != end) {
     delete *begin;
     ++begin;
   }
}

Silly usage scenario (assuming existence of class MyObj):

vector<MyObj*> v;
v.push_back(new MyObj());
v.push_back(new MyObj());
v.push_back(new MyObj());

deleteAll(v.begin(), v.end());

Any tips or references would be greatly appreciated!

Thanks,
-M.D.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]





Author: cbarron413@adelphia.net (Carl Barron)
Date: Thu, 11 Jan 2007 04:04:37 GMT
Raw View
In article <Pine.LNX.4.60.0701101513060.2114@okanagan.cs.ubc.ca>,
Michael Domenic DiBernardo <mddibern@cs.ubc.ca> wrote:

> How might I declare a function that takes a forward_iterator as a
> parameter? I want a generic function that will iterate over a given
> forward iterator and free all of the pointers contained therein.
>
> The gist:
>
> #include <iterator>
>
> void deleteAll(std::forward_iterator begin, std::forward_iterator end) {
>    while (begin != end) {
>      delete *begin;
>      ++begin;
>    }
> }
>
> Silly usage scenario (assuming existence of class MyObj):
>
> vector<MyObj*> v;
> v.push_back(new MyObj());
> v.push_back(new MyObj());
> v.push_back(new MyObj());
>
> deleteAll(v.begin(), v.end());
>
   template <class For>
   void deleteAll(For begin,For end)
   {
      for(;begin!=end;++begin)
      {
         delete *begin;
         // *begin = 0;  // (1)
      }
   }

   will delete the pointers but leave the dangling ptr ok if you if
your std_sequence_container<MyObj *> is going to be cleared immediately
and no copies of these ptrs are going to be dereferenced before going
out of scope.

Safer is a container designed to OWN ptrs stored in it[ boost has one]
, or store some smart pointer in the container to avoid leaving any
pointers dangling...

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]