stl for_each makes two additional copies of functor

S

Sean

#include <iostream>
#include <algorithm>
struct functor {
~functor() {std::cout << 'D';}
void operator()(int a) {std::cout << a;}
};
int main()
{
int a[] = {1,2,3,4,5};
functor f;
std::for_each(a,a+5,f);
}
// produces : 12345DDD

notice the three D's in the output.

The functor is copied once as pass-by-value to for_each()
and once again as the return value from for_each().

Is there a way to use for_each without introducing these
extra copies of the functor? Perhaps this is just a
g++ implementation issue?

Regards,
Sean
 
V

Victor Bazarov

Sean said:
#include <iostream>
#include <algorithm>
struct functor {
~functor() {std::cout << 'D';}
void operator()(int a) {std::cout << a;}
};
int main()
{
int a[] = {1,2,3,4,5};
functor f;
std::for_each(a,a+5,f);
}
// produces : 12345DDD

notice the three D's in the output.

The functor is copied once as pass-by-value to for_each()
and once again as the return value from for_each().

Is there a way to use for_each without introducing these
extra copies of the functor? Perhaps this is just a
g++ implementation issue?


Try

int a[] = {1,2,3,4,5};
const functor &f = functor();
std::for_each(a,a+5,f);

Victor
 
S

Sean

You could use explicit template arguments to specify pass-by-reference
for for_each:

#include <iostream>
#include <algorithm>

struct functor
{
~functor() {std::cout << 'D';}
void operator()(int a) const {std::cout << a;}
};

int main()
{
int a[] = {1,2,3,4,5};
functor f;
std::for_each<int*, functor&>(a,a+5,f);
}

12345D

Not all algorithms may behave as you want, even with this extra effort.
For example see:

http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/lwg-active.html#92

However, if you happen to be a Metrowerks customer, and you're getting
unwanted functor copying even when passing by reference via explicit
template arguments, feel free to report it as a bug to me. We endeavor
to make this idiom work.

Thanks for this helpful information Howard. It seems to me that
pass-by-reference should be the default behavior for for_each. But after
considering the information at the link you provided i can understand
why it is not.

Cheers,
Sean
 

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
474,436
Messages
2,571,696
Members
48,796
Latest member
Greg L.
Top