Using for_each() to deallocate memory

E

Eric Lilja

Hello, I have a std::vector storing pointers to objects that are dynamically
allocated. When I am done with the vector I want to delete all pointers. Can
I use std::for_each() or something to do that in one line? I am so tired of
seeing the following in my code:

for(vector<some_type>::size_type i = 0; i < myvec.size(); ++i)
do_something_with_each_element;

/ Eric
 
M

msalters

Eric said:
Hello, I have a std::vector storing pointers to objects that are dynamically
allocated. When I am done with the vector I want to delete all pointers. Can
I use std::for_each() or something to do that in one line?

Yes - assuimg you have

class deleter_ {
template< typename T > operator()(T* t) { delete t; }
} deleter;

for_each( begin, end, deleter );

Of course, if you try this on int you'll get a message which tells
you that deleter(int) doesn't exist.

HTH,
Michiel Salters
 
V

Victor Bazarov

Eric said:
Hello, I have a std::vector storing pointers to objects that are dynamically
allocated. When I am done with the vector I want to delete all pointers. Can
I use std::for_each() or something to do that in one line? I am so tired of
seeing the following in my code:

for(vector<some_type>::size_type i = 0; i < myvec.size(); ++i)
do_something_with_each_element;

Try it, why doncha?
-------------------------------
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>

struct my_class {};

struct my_alloc {
void operator()(my_class*& p) { p = new my_class; }
};

struct my_dealloc {
void operator()(my_class*& p) { delete p; p = 0; }
};

int main() {
std::vector<my_class*> v(5, (my_class*)0);
std::copy(v.begin(), v.end(),
std::eek:stream_iterator<my_class*>(std::cout, " "));
std::cout << std::endl;
std::for_each(v.begin(), v.end(), my_alloc());
std::copy(v.begin(), v.end(),
std::eek:stream_iterator<my_class*>(std::cout, " "));
std::cout << std::endl;
std::for_each(v.begin(), v.end(), my_dealloc());
std::copy(v.begin(), v.end(),
std::eek:stream_iterator<my_class*>(std::cout, " "));
std::cout << std::endl;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top