我想提交一个句柄,但是我只希望在共享指针仍然有效的情况下执行该句柄:
// 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
我可以slave
在lambda的capture子句中声明吗?像const auto hook = [std::weak_ptr<int> slave = node,=]()....
但不幸的是,这不起作用。我想避免声明变量然后复制它(不是出于性能原因;我只是认为,如果我可以创建lambda所需的任何内容而又不会污染封闭范围,那将变得更加清晰和整洁)。
您可以使用C ++ 14中的广义lambda捕获来执行此操作:
const auto hook = [=, slave = std::weak_ptr<int>(node)]()
{
...
};
这是一个生动的例子。注意,由于没有参数或显式的返回类型,()
因此可以省略空的参数列表()。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句