C ++ this and persistent object

Could you tell me why this code works? There is an overloaded operator () that is used by the replace_if algorithm. In the main function, I created a constant object of the IsEqual class, so only a constant member of the function should be used. Somehow, constancy does not work and this operator is called.

 #include <iostream> #include <vector> #include <algorithm> class IsEqual { int value; public: IsEqual(int v) : value(v) {} bool operator()(const int &elem){ this->value=6; return elem == value; } }; int main() { const IsEqual tst(2); std::vector<int> vec = {3,2,1,4,3,7,8,6}; std::replace_if(vec.begin(), vec.end(), tst, 5); for (int i : vec) std::cout << i << " "; std::cout<<std::endl; } 

result: 3 2 1 4 3 7 8 5

+6
source share
1 answer

std::replace_if will make its own copy of the tst object. It is not required to limit its const .

If you want to use the source object in the algorithm, you can use std::reference_wrapper . Since this applies to the const object, this will result in a compiler error, because the statement requires const :

 std::replace_if(vec.begin(), vec.end(), std::ref(tst), 5); 
+11
source

Source: https://habr.com/ru/post/989950/


All Articles