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

C++ 我可以在lambda capture子句中声明一个变量吗?,c++,c++11,c++14,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()) //

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

// 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
//类中的其他位置:
std::共享的ptr节点;
//稍后:
const std::弱_ptr从(节点);//我可以在capture子句中这样做吗?
常量自动挂钩=[=]()
{
如果(!slave.expired())
//做点什么
其他的
//什么也不要做,班级已经被摧毁了!
};
someService.Submit(hook);//这将在稍后调用,我们不知道该类是否仍然存在

我可以在lambda的capture子句中声明
slave
?类似于
const auto hook=[std::weak_ptr slave=node,=]()…
但不幸的是这不起作用。我希望避免声明变量然后复制它(不是出于性能原因;我只是认为如果我可以创建lambda所需的任何内容而不污染封闭范围,这将更加清晰和整洁)。

您可以使用C++14中的广义lambda捕获来实现这一点:

const auto hook = [=, slave = std::weak_ptr<int>(node)]()
{
    ...
};
const auto hook=[=,slave=std::弱(节点)]()
{
...
};
这是一个例子。请注意,由于没有参数或显式返回类型,因此可以省略空参数列表(
()
)。

在C++14中可以这样做

如果您愿意修改捕获的值,只需添加
mutable
说明符即可。 下面是一个从零到向量长度填充向量的示例

#include <iostream>
#include <vector>
#include <algorithm>


int main()
{
    std::vector<int> container(10);

    std::generate(container.begin(), container.end(), [n = 0]() mutable { return n++; });

    for (const auto & number : container)
    {
        std::cout << number << " ";
    }

    std::cin.ignore();

    return 0;
}
#包括
#包括
#包括
int main()
{
std::载体容器(10);
std::generate(container.begin(),container.end(),[n=0]()可变{return n++;});
用于(常数自动和编号:容器)
{

std::只能在C++14中使用,很抱歉。@chris啊……我已经添加了C++1y标志,所以如果你想添加它作为答案,我会标记它。干杯。回答好,+1。只是一个小的添加:如果你想更改lambda中捕获的变量(例如调用一个非常量方法),lambda必须是
可变的。