c++ - 我可以在 lambda 捕获子句中声明一个变量吗?

标签 c++ c++11 c++14

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

// 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 所需的任何内容会更清晰、更整洁)。

最佳答案

您可以使用 C++14 中的通用 lambda 捕获来做到这一点:

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

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

关于c++ - 我可以在 lambda 捕获子句中声明一个变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852309/

相关文章:

c++ - 重复排列的排名和取消排名

c++ - 如何在std算法中使用unique_ptr的transform_iterator

c++ - 如何将 priority_queue 与类实例的非静态比较方法一起使用?

c++ - 如何在 C++14 中实现读/写锁

c++ - 如何将 MPI 与 QT 一起使用?

c++ - 通过 map C++

c++ - C++ 中的按位数学运算

c++ - 命名空间名称在范围内必须是唯一的。为什么?

c++ - 有没有办法强制自动推导考虑 operator <some_type>() 而不是复制赋值?

c++ - 使用 boost hana 定义结构时出现编译错误