std::find_if function

Hi,

In the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Larger_than {
int v;

public:
Larger_than(int vv) : v(vv) { }
bool operator()(int x) const {return x>v; }
};

int main() {

vector<int> v {3,5,7,8,9,12};
find_if(v.begin(), v.end(), Larger_than(31);
...
}



What happens here please?
I think, in the first iteration the constructor will be called with the temporary object Larger_than(31) so Larger_than::v becomes 31 and the operator function will be called in that first iteration as well and it does the comparison. In the next iteration only that operator is called and it continues until the end of the iteration.

Is it right?
Last edited on
"As-if"
a. the constructor for the temporary object Larger_than(31) is called (line 12)
b. the copy of this temporary object is passed to find_if (copy/move constructor)
c. find_if may construct and after use destroy any number (zero or more) of additional copies of the object of type Larger_than
d. the copy that the function receives is destroyed when it returns
e. the temporary object created on line 12 is destroyed at the end of the full expression
http://coliru.stacked-crooked.com/a/e91457b77a5e27fc

In practice, unless the construct/copy/move/destroy of these objects have observable side effects, no object will be created (and the entire function would be inlined)
https://godbolt.org/g/s9334n
I tested the code by VS 2917. Its output is much simpler and more natural (seemingly).
When the statement on line 12 is executed, first it goes and creates a temp object of the class. Then, it goes to the operators()(int). That operator will be invoked 6 times (because we have 6 elements in the vector v. And at the end the destructor is called.
Thanks.
Topic archived. No new replies allowed.