以下编译。但是,有没有悬而未决的参考问题?
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当然更复杂。)
但是,有没有悬而未决的参考问题?
那完全取决于你在做什么Foo
。下面是一个例子将有悬空引用问题:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句