【问题标题】:C++ using this pointer with bind inside lambda functionC++ 在 lambda 函数中使用 this 指针和绑定
【发布时间】:2016-02-24 05:59:50
【问题描述】:

我正在使用 std::bind 在 lambda 函数中绑定一个成员函数,代码如下:

class A {
...
...

public:
   foo(function<void()> f) {

   }
...
...
};

class B {
...
...
A a;
public:
   B_function_1(){
      a.foo([](){
         some_other_function(bind(&B::B_function_2, this, _1,_2));
   }
...
private:
   B_function_2(arg1, arg2) {
   ...
   }
};

我的问题是当我尝试编译时出现此错误:

error: ‘this’ was not captured for this lambda function

在我的例子中,这是指当前类(B 类)。 所以,我的问题是这里有什么问题?我错过了什么?

谢谢。

【问题讨论】:

  • 错误信息就在那里说。 this 未被捕获。你需要捕捉它。

标签: c++ lambda this bind


【解决方案1】:

要在 lambda 中捕获 this 指针,请使用 a.foo([this]()

[this] 按值捕获 this 指针 [&] 通过引用捕获 lambda 主体中使用的所有自动变量 odr

来自文档

【讨论】:

  • 是的,正在重新粘贴。正在尝试从文档中复制粘贴 :)
  • [] 不捕获任何内容(或者,焦土策略?) [&] 通过引用捕获任何引用的变量 [=] 通过复制捕获任何引用的变量 [=, &foo] 捕获任何引用的变量通过复制,但通过引用捕获变量 foo [bar] 通过复制捕获 bar;不要复制任何其他内容 [this] 捕获封闭类的 this 指针
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多