问题描述
假设我使用lambda作为回调函数,并且在创建lambda时,我通过引用捕获了局部函数变量。现在假设lambda对象直到该局部函数变量超出范围后才执行。会发生什么事?
Suppose I use a lambda as a callback function, and when creating the lambda, I capture a local function variable by reference. Now suppose that the lambda object does not get executed until after that local function variable goes out of scope. What happens?
我意识到,如果有可能发生某人这样做,这将是非常愚蠢的,但是我几乎肯定,某人最终会这样做
I realize that it would be pretty stupid for someone to do so if there's a chance of it happening, but I am almost positive that someone would end up doing it.
推荐答案
是的,那将是悬空的引用。听起来您在担心界面设计:几乎可以肯定,有人最终会这样做。请不要在此基础上拒绝lambda和 std :: function
,因为它们比其他任何方法都没有危险。 Lambda只是定义局部函子的一种简单方法。 std :: function
是持久性,多态函子或非lambda的最佳接口。
Yes, that would be following a dangling reference. It sounds like you're worried about interface design: "I am almost positive that someone would end up doing it." Please don't reject lambdas and std::function
on this basis, as they are no more dangerous than any other alternative. Lambdas are just a simpler way to define local functors. std::function
is the best interface to persistent, polymorphic functors, lambda or not.
范围问题是为什么更容易按价值捕获。除非他们写&
,否则用户不会获得参考。当然,危险是有人会习惯用 [&]
启动其所有lambda函数,因为引用更快。希望任何这样的人都能尽快学到他们的课程……尽管有些指针指针快乐的人简直是不可救药。
The scope issue is why it's easier to capture by value. The user won't get a reference unless they write &
. Of course, the danger is that someone would get in the habit of starting all their lambda functions with [&]
, since references are "faster." Hopefully any such person would learn their lesson soon enough… although some pointer-happy folks are just incorrigible.
这篇关于如果我通过引用捕获局部变量,并且超出范围,会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!