Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

c++ - What happens if I capture a local variable by reference, and it goes out of scope?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...