在C ++ 11 Lambdas中,如果我通过引用捕获局部变量,并且它超出范围会发生什么? [英] In C++11 Lambdas, what happens if I capture a local variable by reference, and it goes out of scope?

查看:350
本文介绍了在C ++ 11 Lambdas中,如果我通过引用捕获局部变量,并且它超出范围会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用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.

推荐答案

是的,这将是一个悬挂的引用。听起来你担心界面设计:我几乎是肯定的,有人会最终这样做。请不要在此基础上拒绝lambdas和 std :: function ,因为它们不比任何其他替代品更危险。 Lambdas只是一个更简单的方法来定义局部函子。 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.

这篇关于在C ++ 11 Lambdas中,如果我通过引用捕获局部变量,并且它超出范围会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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