下列 编译。但是,有没有任何悬挂参考问题?
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当然更复杂。)
下列 编译。但是,有没有任何悬挂参考问题?
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
lambda表达式 [&foo](int i){f(i, foo);}
将导致编译器生成类似这样的闭包类(但不完全正确):
class _lambda
{
Foo& mFoo; // foo is captured by reference
public:
_lambda(Foo& foo) : mFoo(foo) {}
void operator()(int i) const
{
f(i, mFoo);
}
};
因此,申报 Foo foo([&foo](int i){f(i, foo);});
被视为 Foo foo(_lambda(foo));
。捕获 foo
本身在构造时在这种情况下没有问题,因为这里只需要它的地址(引用通常通过指针实现)。
方式 std::function<void(int)>
将在内部复制构造此lambda类型,这意味着Foo的构造函数参数 fn
持有一份副本 _lambda
对象(保存一个引用(即mFoo)) foo
)。
这些暗示在某些情况下可能会出现悬挂参考问题,例如:
std::vector<std::function<void(int)>> vfn; // assume vfn live longer than foo
class Foo {
Foo(std::function<void(int)> fn) { vfn.push_back(fn); }
}
void f(int i, Foo& foo) { /* stuff with i and foo */ }
Foo foo([&foo](int i){f(i, foo);});
....
void ff()
{
// assume foo is destroyed already,
vfn.pop_back()(0); // then this passes a dangling reference to f.
}