不知道如何更好地描述它.这是代码.这无法在gcc 4.9.2(Debian 8.5)上进行编译,我认为它很难在以前的版本中编译.只有当我在lambda设置中访问后来声明的结构的成员作为默认参数时,问题似乎才会发生.其他显示的案例工作.
// Test program
class C1
{
private:
// Forward-declared
struct S_Private;
S_Private* d_;
public:
void func();
};
struct C1::S_Private
{
int a;
};
void C1::func()
{
// This will work
int test = d_->a;
// Accessing the d_->a as a default argument in lambda setup
// will NOT work:
// error: invalid use of non-static data member ‘C1::d_’
auto some_lambda = [&](int arg = d_->a)
{
// This will also work
int test2 = d_->a;
};
}
int main(void)
{
}
Run Code Online (Sandbox Code Playgroud)
不幸的是auto some_lambda = [&](int arg = d_->a)
,在 中,d_->a
不是d_->a
您之前在函数中使用的,而是在您使用捕获的d_->a
上调用的。因为它是一个成员变量,所以不能将它用作函数中的默认参数。this
[&]
本质上
auto some_lambda = [&](int arg = d_->a)
{
// This will also work
int test2 = d_->a;
};
Run Code Online (Sandbox Code Playgroud)
是
struct some_unique_name
{
some_unique_name(C1*& var) : this_(var) {}
auto operator()(int arg = this_->d_->a)
{
// This will also work
int test2 = d_->a;
}
C1*& this_;
};
auto some_lambda = some_unique_name{this};
Run Code Online (Sandbox Code Playgroud)
正如您从翻译中看到的,它使用类成员,而不是类本身中的对象。