我在下面有一个小例子,它有两个返回std :: function的函数(getFoo1 ... 2).
我关心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)
亲切的问候,
维尔纳
这是旧版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)