[英]passing pointer to std::function<void()>
在[]
传递指向std::function<void()>
的指针时,避免UB的最佳实践是什么?
如果未删除对象,则cls_ptr
在second_on_finish
始终有效吗?
这是当前代码:
void Foo()
{
SomeClass* cls_ptr = GetPointerToClass();
std::function<void()> first_on_finish = [cls_ptr]() {
if (some_argument == true)
{
std::function<void()> second_on_finish = [cls_ptr]() {
//cls_ptr is always valid here?
};
run_in_a_few_seconds(second_on_finish);
}
};
run_in_a_few_seconds(first_on_finish);
}
如果未删除对象,则cls_ptr在second_on_finish中将始终有效
如果您的意思是cls_ptr
没有销毁-答案是肯定的 。 指针是通过值(而不是它指向的对象)捕获的,因此直到该地址处的对象被破坏为止,您可以将其引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.