[英]Why can't I declare a struct variable inside a lambda in c++0x?
[英]Can I declare a variable inside a lambda capture clause?
我想提交一個句柄,但我只希望在共享指針仍然有效時執行它:
// 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的capture子句中聲明slave
嗎? 像const auto hook = [std::weak_ptr<int> slave = node,=]()....
但遺憾的是這不起作用。 我想避免聲明變量然后復制它(不是出於性能原因;我只是認為如果我可以創建lambda需要的任何東西而不污染封閉范圍,它會更清晰和更整潔)。
您可以使用C ++ 14中的通用lambda捕獲來執行此操作:
const auto hook = [=, slave = std::weak_ptr<int>(node)]()
{
...
};
這是一個實例 。 請注意,由於沒有參數或顯式返回類型,因此可以省略空參數列表( ()
)。
正如克里斯所提到的,這在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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.