问题 我可以在lambda capture子句中声明一个变量吗?


我想提交句柄,但我只希望在共享指针仍然有效时执行它:

// elsewhere in the class:
std::shared_ptr<int> node;

// later on:
const std::weak_ptr<int> slave(node); // can I do this in the capture clause somehow?
const auto hook = [=]()
{
  if (!slave.expired())
    //do something
  else
    // do nothing; the class has been destroyed!
};

someService.Submit(hook); // this will be called later, and we don't know whether the class will still be alive

我可以申报吗? slave 在lambda的捕获子句中?就像是 const auto hook = [std::weak_ptr<int> slave = node,=]().... 但不幸的是,这不起作用。我想避免声明变量然后复制它(不是出于性能原因;我只是认为如果我可以创建lambda需要的任何东西而不污染封闭范围,它会更清晰和更整洁)。


12123
2018-04-04 02:14


起源

抱歉,仅在C ++ 14中。 - chris
@chris啊...好吧我已经添加了c ++ 1y标志,所以如果你想添加它作为答案我会标记它。干杯。 - quant


答案:


您可以使用C ++ 14中的通用lambda捕获来执行此操作:

const auto hook = [=, slave = std::weak_ptr<int>(node)]()
{
    ...
};

这是一个 实例。请注意,由于没有参数或显式返回类型,因此空参数列表(())可以省略。


14
2018-04-04 02:27



好的答案,+ 1。只是一个小小的补充:如果想要在lambda中更改捕获的变量(例如调用非const方法),lambda必须是 mutable。 - davidhigh