https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112544
Bug ID: 112544 Summary: Lambda returned from a factory function is not trivially copyable in some (weird) cases Product: gcc Version: 14.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: philodej at gmail dot com Target Milestone: --- See a minimal example in compiler explorer (including the comments): - https://godbolt.org/z/b3WdfrKMY The issue is demonstrated on trunk, but goes back to at least version 6. As a consequence the std::function sometimes incorrectly detects its _Local_storage constant, which leads not only to a sub-optimal performance (unnecessary heap allocations), but also a incorrect code in some build configurations. Additional notes: We encountered ASAN detected memory leaks (the reason seems to be that std::function constructor decides to allocate buffer, but destructor does not delete the dynamically allocated memory as it thinks that closure is stored in local storage). We also encountered a FPE due to this bug in the past. It was never fully understood, just seized to demonstrate thanks to a refactoring leading to a different memory layout of the lambda closure. But again the primary reason was probably a memory corruption due to _Local_storage inconsistency inside the std::function. I am not sure how the inconsistency actually happens, but it seems that std::function construction and destruction have a different opinion whether the closure is supposed to be stored locally or not. I am reporting it as a compiler bug (as opposed to a library bug) as I believe that std::function encountered issues are just a consequence of the primary reason (__is_location_invariant/is_trivially_copyable inconsistency).