2014-04-04 34 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。請注意,由於沒有參數或顯式返回類型,因此可以省略空參數列表(())。

相關問題