2014-04-04 36 views
7

我希望提交一个手柄,但我只希望它如果共享指针仍然有效执行:我可以在lambda捕获子句中声明一个变量吗?

// 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 

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

+3

只有在C++ 14中,很抱歉地说。 – chris

+0

@chris啊......好吧,我已经添加了C++ 1y标志,所以如果你想添加一个答案,我会标记它。干杯。 – arman

回答

10

为此,您可以使用通用的λ抓住了C++ 14:

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

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

相关问题