https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109538
Bug ID: 109538 Summary: Spurious -Werror=dangling-reference false positive Product: gcc Version: 13.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: mr...@courier-mta.com Target Milestone: --- gcc 13.0.1 would like to register a complaint: t.C:17:14: error: possibly dangling reference to a temporary [-Werror=dangling-reference] 17 | const int &v=optional_arg_or(def, 0); | ^ t.C:17:31: note: the temporary was destroyed at the end of the full expression ‘optional_arg_or(def, 0)’ 17 | const int &v=optional_arg_or(def, 0); | ~~~~~~~~~~~~~~~^~~~~~~~ for: #include <optional> #include <utility> const int &optional_arg_or(std::optional<int> &def, int &&def_val) { def = def_val; return *def; } int gimme() { std::optional<int> def; const int &v=optional_arg_or(def, 0); int bologna=v; return bologna; } Changing optional_arg_or's parameter to "int def_val" silences the complaint. gcc appears to be voicing an objection that optional_arg_or returns a reference to a temporary that gets created during the function call and destroyed at the conclusion of the function call. However that temporary gets placed into a std::optional, and then a reference to the std::optional gets returned.