Re:Implementing Go's defer keyword in C++
by junke on Saturday October 21, 2017 @04:53PM
(#15523567)
I am not sure capturing variables by reference implements the expected behavior; what would the equivalent C++ code return for this Go example?
[ Parent
| on HN ]
Re:Implementing Go's defer keyword in C++
by JBReefer on Saturday October 21, 2017 @04:56PM
(#15523584)
Wouldn't this work by reference? The referenced value would be the same in both contexts.
Honestly, am I missing something?
Re:Implementing Go's defer keyword in C++
by parenthephobia on Saturday October 21, 2017 @05:12PM
(#15523647)
The syntax of defer is a function call, but it isn't called like a normal function: the arguments are evaluated at the time the defer is encountered, and then the function is called later. That's one reason why defer is very often called with an anonymous function, so that variables can be captured.
So, the version that prints 1 is
func a() {
i := 0
defer func(){
fmt.Println(i)
}()
i++
return
}