https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92679
--- Comment #2 from Jonathan Wakely <redi at gcc dot gnu.org> --- Without optimisation it prints your expected output for me (with any version of GCC). It only fails with optimisation. ASan seems to show a problem in your code: ==428329==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7ffcfe3b22f0 at pc 0x0000004060c0 bp 0x7ffcfe3b1be0 sp 0x7ffcfe3b1bd8 READ of size 8 at 0x7ffcfe3b22f0 thread T0 #0 0x4060bf in std::_Function_base::_M_empty() const /home/jwakely/gcc/8/include/c++/8.3.1/bits/std_function.h:260 #1 0x4060bf in std::function<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > (int&)>::operator()(int&) const /home/jwakely/gcc/8/include/c++/8.3.1/bits/std_function.h:685 #2 0x4060bf in any_visitor<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::accept<int>(std::function<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > (int&)>)::{lambda(std::any&)#1}::operator()(std::any&) const /tmp/92679.cc:18 #3 0x4060bf in std::_Function_handler<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > (std::any&), any_visitor<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::accept<int>(std::function<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > (int&)>)::{lambda(std::any&)#1}>::_M_invoke(std::_Any_data const&, std::any&) /home/jwakely/gcc/8/include/c++/8.3.1/bits/std_function.h:283 #4 0x407187 in std::function<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > (std::any&)>::operator()(std::any&) const /home/jwakely/gcc/8/include/c++/8.3.1/bits/std_function.h:687 #5 0x407187 in any_visitor<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::operator()(std::any&) /tmp/92679.cc:26 #6 0x4032d0 in main /tmp/92679.cc:45 #7 0x7fe45c0001a2 in __libc_start_main ../csu/libc-start.c:308 #8 0x4023cd in _start (/tmp/a.out+0x4023cd)