本文介绍了C ++ lambda构造函数参数可以捕获构造的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下编译。但是是否有任何悬挂的引用问题?

The following compiles. But is there ever any sort of dangling reference issue?

    class Foo {
         Foo(std::function<void(int)> fn) { /* etc */ }
    }

    void f(int i, Foo& foo) { /* stuff with i and foo */ }

    Foo foo([&foo](int i){f(i, foo);});

看起来工作。 (真正的lambda当然更复杂。)

Seems to work. (The real lambda is of course more complicated.)

推荐答案

这完全取决于你在做什么 Foo 。以下是

That depends entirely on what you're doing with Foo. Here's an example that would have dangling reference issues:

struct Foo {
     Foo() = default;
     Foo(std::function<void(int)> fn) : fn(fn) { }
     std::function<void(int)> fn;
}

Foo outer;
{
    Foo inner([&inner](int i){f(i, inner);});
    outer = inner;
}
outer.fn(42); // still has reference to inner, which has now been destroyed

这篇关于C ++ lambda构造函数参数可以捕获构造的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:48