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.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…