Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ this and constant object

could you tell me why this code works? There is overloaded operator() which is used by replace_if algorithm. In main function I've created constant object of IsEqual class so only constant function member should be used. Somehow constancy isn't working and that 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

like image 887
Joker Avatar asked Jun 29 '15 14:06

Joker


People also ask

What is a constant object?

An object of a class may be declared to be const , just like any other C++ variable. For example: const Date birthday(7, 3, 1969); declares a constant object of the Date class named birthday .

How do you declare a constant object in C++?

A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error.

Can C functions be constant?

Not in standard C, since there are no classes or objects (as in "class instances, i.e. collections of data with associated functions"), there's nothing for the function to be const "against".

When called by its object a member function declared as const?

If you declare a member function const, you tell the compiler the function can be called for a const object. A member function that is not specifically declared const is treated as one that will modify data members in an object, and the compiler will not allow you to call it for a const object.


1 Answers

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

If you want to use the original object in the algorithm, you can use an std::reference_wrapper. Since it would be referring to a const object,this would result in a compiler error because it would require the operator to be const:

std::replace_if(vec.begin(), vec.end(), std::ref(tst), 5);
like image 51
juanchopanza Avatar answered Oct 12 '22 09:10

juanchopanza