C ++ lambda构造函数参数可以捕获构造的变量吗? [英] Can a C++ lambda constructor argument capture the constructed variable?

查看:197
本文介绍了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.)

推荐答案


dangling reference issue?

But is there ever any sort of dangling reference issue?

这完全取决于你在做什么 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构造函数参数可以捕获构造的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆