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

Viewed 76

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 of localVar)
            memberVar = 100; // allowed (const copy of this pointer - NOT const *this copy)
            };
        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...

2 Answers

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

Because member variables aren't captured at all by a default capture. What is captured is this pointer. And that is "const": You cannot modify this. But in a non-const member function it is a pointer to non-const and thus you can modify the non-const members.

You're right, this is a lame behavior.

That's why in C++20 the implicit capture of this (i.e. by reference) is deprecated when the capture-default is =.

Presumably the intent is to change = one day to capture *this (i.e. by value).

Related