Werner Erasmus
Werner Erasmus

Reputation: 4076

lambdas: this capture ignores constness (vs std::bind)

I have a little example here below that has two functions (getFoo1...2) that returns a std::function.

I'm concerned with regards to the lambda behaviour (I EXPECTED IT TO NOT COMPILE, AS WITH getFoo2). Any insights would be welcome.

Note: Compiler used GCC 4.8.*.

#include <iostream>
#include <functional>

struct X
{
    void foo(){ std::cout << " non const !!!! foo called" << std::endl;}

    std::function<void()> getFoo1() const
    {
        //Compiles, even though "non const" this required...
        return [this]{foo();};
    }

    std::function<void()> getFoo2() const
    {
        //Fails to compiler due to non const this required
        return std::bind(&X::foo, this);
    }
};

int main() 
{

    X().getFoo1()();
    X().getFoo2()();
    return 0;
}

Kind regards,

Werner

Upvotes: 3

Views: 225

Answers (1)

ecatmur
ecatmur

Reputation: 157344

This is a defect in older versions of gcc. Versions of gcc from 5.1.0 onwards, and of other compilers (clang, MSVC, ICC) correctly refuse to compile the code.

main.cpp: In lambda function:
main.cpp:11:27: error: passing 'const X' as 'this' argument discards qualifiers [-fpermissive]
         return [this]{foo();};
                           ^
main.cpp:6:10: note:   in call to 'void X::foo()'
     void foo(){ std::cout << " non const !!!! foo called" << std::endl;}
          ^

Upvotes: 7

Related Questions