我想提交句柄,但我只希望在共享指针仍然有效时执行它:
// 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的捕获子句中?就像是 const auto hook = [std::weak_ptr<int> slave = node,=]()....
但不幸的是,这不起作用。我想避免声明变量然后复制它(不是出于性能原因;我只是认为如果我可以创建lambda需要的任何东西而不污染封闭范围,它会更清晰和更整洁)。