Reputation: 439
I want just to print a vector with for_each.
using namespace std;
struct Print {
int z = 0;
void operator()(int i) {
if (z) cout << ' ';
cout << i;
z = 1;
}
~Print() {
if (z) cout << endl;
}
};
main() {
vector<int> v = {1, 2, 3, 4, 5};
for_each(begin(v), end(v), Print());
}
It works wrong, it calls destructor two times and prints two newlines instead of one. Why? Can anybody explain the logic of this odd behavior? BTW it works fine with the ugly global variable.
int z;
struct Print {
void operator()(int i) {
. . .
};
I am using GCC.
Upvotes: 1
Views: 66
Reputation: 385295
It's not "wrong". You forgot that the predicate is copied, at least once. In fact, it is legal for the predicate to be copied many times. Your class should take that into account; and not by making its members static
(which breaks subsequent invocations). std::for_each
is not really the right tool for this job.
Upvotes: 3
Reputation: 439
I found much better solution. Both constructors should be explicitly included into Print class.
Print() {}
Print(const Print&) {}
Thanks to Bo Persson and Gene who explained the logic.
Upvotes: 0
Reputation: 92341
Check the signature of for_each
template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
It returns a copy of the function object.
Upvotes: 1