lambdas:这个捕获忽略了constness(vs std :: bind)

Wer*_*mus 2 c++ c++11

我在下面有一个小例子,它有两个返回std :: function的函数(getFoo1 ... 2).

  • 在这两种情况下,getter都是const.
  • getFoo1通过使用带有此捕获的lambda生成返回类型.
  • getFoo2使用std :: bind生成返回类型.
  • 在这两种情况下,实际函数都是非常量的.
  • lambda案例编译得很好(因此constness丢失了......).
  • 绑定器抱怨这个的constness(正如预期的那样,因为成员函数指针是非const并且需要非const T绑定).

我关心lambda行为(我预计它不会编译,与getFoo2一样).任何见解都会受到欢迎.

注意:编译器使用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;
}
Run Code Online (Sandbox Code Playgroud)

亲切的问候,

维尔纳

eca*_*mur 7

这是旧版gcc中缺陷.从5.1.0开始的gcc版本以及其他编译器(clang,MSVC,ICC)的版本正确拒绝编译代码.

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;}
          ^
Run Code Online (Sandbox Code Playgroud)