Analyse a C++ fanctor

Hello all,

Here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using namespace std;

template<typename T>
class Less_thane {
	const T val;

public:
	Less_thane(const T& v) : val(v) { }
	bool operator ()(const T& x) const { return x < val; }
};

template<typename C, typename P>
int myCount(const C& c, P pred) {
	int cnt = 0;
	for (const auto& x : c)
		if (pred(x))
			cnt++;
	return cnt;
}

int main()
{
	vector<int> vi{ 1, 2, 4, 5, 6, 7, 8 };
	cout << "number of valuse less than 5 = " << myCount(vi, Less_thane(5)) << endl;
	cin.get();
	return 0;
}


For each x in the for loop in myCount, a temporary object with the value 5 is created to which the x is compared. Right?
Last edited on
Apparently not.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>
using namespace std;

template<typename T>
class Less_thane {
	const T val;

public:
  Less_thane(const T& v) : val(v) {
    cout << "Made a new " << v << endl;
  }
  bool operator ()(const T& x) const { return x < val; }
};

template<typename C, typename P>
int myCount(const C& c, P pred) {
	int cnt = 0;
	for (const auto& x : c)
		if (pred(x))
			cnt++;
	return cnt;
}

int main()
{
	vector<int> vi{ 1, 2, 4, 5, 6, 7, 8 };
	cout << "number of valuse less than 5 = " << myCount(vi, Less_thane<int>(5)) << endl;
	cin.get();
	return 0;
}

$ g++ -std=c++17 foo.cpp
$ ./a.out 
Made a new 5
number of valuse less than 5 = 3


And did you really save anything by omitting to post code with the two include files edited out "for brevity"?

Yes, I omitted the two lines for briefness.

So seemingly only one time a temporarily Less_thane object is created not for each item of the vector. But where exactly will that object be created in the code?
> int myCount(const C& c, P pred)
Well considering that your 'P' is a pass-by-value thing, the temporary will likely be constructed in the stack frame that main creates to call myCount.

You could always add similar debug cout statements for your default ctor, your dtor and maybe even your copy-ctor(s).

But remember, C++ compilers optimise aggressively, so what might seem obvious and apparent in this simple example might not hold true for all cases of Less_thane, and even less so across all compilers.

> Yes, I omitted the two lines for briefness.
And in doing so, you turned an easy copy/paste/compile into something that becomes annoying enough for people to ignore.
> Yes, I omitted the two lines for briefness.
well, don't do that

> But where exactly will that object be created in the code?
1
2
3
4
5
6
7
cout
   << "number of valuse less than 5 = "
   << myCount(
      vi,
      Less_thane<int>(5) /*here*/
   )
   << endl;
although you pass that object by copy to the function, I suppose that may be optimised out.
¿where do you think there is another creation?
I got it, thank you.
Topic archived. No new replies allowed.