for_each() function!

Why the function for_each() calls first the constructor and after the function operator()?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <algorithm>
using namespace std;
 
struct A
{
	A() { sum = 0; cout << "Called constructor" << endl; }
	
    void operator()(char n)
    { cout << n; cout << "Called operator()" << endl; }
    
    int sum;
};
 
int main()
{
	char s[]="Hello World!";
	for_each < char*, A > (s, s+sizeof(s), A());
} 
You called the default constructor, from the expression A()

std::for_each could also potentially call A's copy constructor twice (for the pass-by-value parameter and for by-value return), but the first call is optimized out and the return was unused in your case.

(by the way, since you appear to be accumulating a sum, you need to save the return of for_each, or just use std::accumulate)

Incidentally, those template arguments are unnecessary, it's just A result = for_each(s, s+sizeof(s), A());
Last edited on
Because the arguments of the functions must be evaluated before the function starts.

Also, ¿how do you expect to call the non-static member function without an object?
Topic archived. No new replies allowed.