Constant-correctness with function members

80 Views Asked by At

The class TestConst has a member set of type std::function<void(double)>. The setter method is marked as const but it still modifies the internal private variable m_value.

class TestConst {
public:
    void setter(double v) const {
        set(v);
    }
    
private:
    double m_value = 1;
    std::function<void(double)> set = [this](double v) {m_value = v;};
};

Why does the compiler (g++ 10.2) allows that without any errors or warnings?

1

There are 1 best solutions below

12
molbdnilo On BEST ANSWER

The capture of this isn't const, and the member isn't modified by *this but through an indirection.

This is the same situation:

class TestConst {
public:
    void setter(double v) const {
        sneaky.set(v);
    }
    
private:
    double m_value = 1;
    struct
    {
         TestConst* that;
         void set(double v) const { that->m_value = v; }
    } sneaky{ this };
};