我想提交一个句柄,但我只希望在共享指针仍然有效时执行它:
// 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
Run Code Online (Sandbox Code Playgroud)
我可以slave在lambda的capture子句中声明吗?有点像const auto hook = [std::weak_ptr<int> slave = node,=]()....但不幸的是这不起作用.我想避免声明变量然后复制它(不是出于性能原因;我只是认为如果我可以创建lambda需要的任何东西而不污染封闭范围,它会更清晰和更整洁).
chr*_*ris 17
您可以使用C++ 14中的通用lambda捕获来执行此操作:
const auto hook = [=, slave = std::weak_ptr<int>(node)]()
{
...
};
Run Code Online (Sandbox Code Playgroud)
这是一个实例.请注意,由于没有参数或显式返回类型,()因此可以省略空参数列表().
正如chris所提到的,这在 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2576 次 |
| 最近记录: |