AlQuemist
AlQuemist

Reputation: 1304

Constant-correctness with function members

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?

Upvotes: 1

Views: 82

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

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 };
};

Upvotes: 3

Related Questions