c++ - Reference captured in static variable definition -


#include <iostream>  void foo(int k) {     static auto bar = [&]{         std::cout << k << std::endl;     };     bar(); }  int main () {     foo(1); foo(2); foo(3); // output correct: 1, 2, 3 } 

check function foo, how static lambda capturing k reference. seems work, , same happening more complicated datatypes rather int.

is expected? there guarantee address of k same every invocation of foo, or ub?

thanks in advance, , sorry if answered (i did try find similar question without success)

it undefined behavior.

per paragraph 5.2.2/4 of c++11 standard function call expressions , initialization of parameters:

[...] the lifetime of parameter ends when function in defined returns. initialization , destruction of each parameter occurs within context of calling function. [...]

therefore, lambda storing reference becomes dangling function call returns.

in case, implementations free (and likely) create function parameters @ same address each function call, reason why observing expected output.

however, behavior not mandated standard - therefore, should not rely on (if case, code legal because of 3.8/7).


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -