将指针传递给 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);
}
最佳答案
will the cls_ptr always be valid in the second_on_finish if the object isnt deleted
如果您的意思是 cls_ptr
到那时还没有被销毁 - 答案是是的。指针是按值(而不是它指向的对象)捕获的,因此直到对象在该地址被销毁 - 您可以引用它。
关于c++ - 将指针传递给 std::function<void()>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55725113/