c++ - 将指针传递给 std::function<void()>

标签 c++

将指针传递给 std::function<void()> 时避免 UB 的最佳做法是什么?在[]

cls_ptrsecond_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/

相关文章:

c++ - 此函数期望从 std::istream 解析什么格式的输入?

c++ - 将调用两个重载模板中的哪一个?

c++ - 从现有 cmake 应用程序导入的 Netbeans 项目无法在 Windows 上生成文件系统错误

c++ - 我们可以实现一个 max 或 min 宏,它可以接受可变参数(超过两个参数)

c++ - 整数和寄存器大小之间有关系吗?

c++ - 在给定矩阵中找到最大的盆地大小

c++ - 用 wxWidgets 绘图

c++ - 如何使用离屏 DC 一次渲染所有位图的汇编?

C++ 比较两个具有相同持续时间的 std::chrono::time_points 失败

c++ - 如何部分禁用 C4244