Link taken in the definition of a static variable

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

Check the foo function, as a static lambda captures k by reference. This seems to work, and the same thing happens with more complex data types, not int.

Is this expected? Is there any guarantee that the address k will be the same for every call to foo, or is it UB ?

Thanks in advance, and sorry if this was previously answered (I tried to find a similar question without success)

+8
c ++ c ++ 11
source share
2 answers

This is Undefined Behavior .

In paragraph 5.2.2 / 4 of the C ++ 11 standard on expressions for calling functions and initializing their parameters:

[...] The lifetime of the parameter ends when the function in which it is defined return . The initialization and destruction of each parameter occurs in the context of the calling function. [...]

Therefore, your lambda will store a link that becomes dangling as soon as the function call returns.

In this case, the implementations are free (and probably) for creating functional parameters at the same address for each function call, which is probably the reason that you are seeing the expected result.

However, this standard requirement is not provided, so you should not rely on it (if that were the case, your code would be legal due to 3.8 / 7).

+4
source share

The reason it probably "works" in your example is because the call stack always lines up the same way. Try this instead and see if you all get the expected result.

 #include <iostream> void foo(int k) { static auto bar = [&]{ std::cout << k << std::endl; }; bar(); } void baz(int k) { std::cout << "baz: "; foo(k); } int main () { foo(1); baz(2); foo(3); } 
+1
source share

All Articles