samedi 10 juillet 2021

Why default capture is not consistently const for both local variables and member variables?

I'm curious what's the story behind following inconsistency with passing default parameters:

struct Example {
    void run() {
        int localVar = 0;
        auto l = [=](){
            // localVar = 100; Not allowed (const copy)
            memberVar = 100; // allowed (& to this)
            };
        l();
    }
    int memberVar = 1;
};

Why not pass all parameters to lambda capture by const value (including const *this)?

Is that a desirable design choice, or result of a implementation limitation?

EDIT:

I know const pointer to the object is passed as a parameter and the object itself can be modified but the pointer itself cannot. But this is implementation detail that has to be known to the reader and is not obvious from the first look. Consistent from my subjective perspective would be capturing this by const value...

Aucun commentaire:

Enregistrer un commentaire