diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc index 951b9fd2a88dea0aa66d73762d979c63cf65aeff..c7c7a122045cf868c526320ba3a3534e37839529 100644 --- a/gcc/cp/call.cc +++ b/gcc/cp/call.cc @@ -13539,6 +13539,13 @@ maybe_warn_dangling_reference (const_tree decl, tree init) return; if (!TYPE_REF_P (TREE_TYPE (decl))) return; + /* Don't suppress the diagnostic just because the call comes from + a system header. If the DECL is not in a system header, or if + -Wsystem-headers was provided, warn. */ + auto wsh + = make_temp_override (global_dc->dc_warn_system_headers, + (!in_system_header_at (DECL_SOURCE_LOCATION (decl)) + || global_dc->dc_warn_system_headers)); if (tree call = do_warn_dangling_reference (init)) { auto_diagnostic_group d; diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference4.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference4.C new file mode 100644 index 0000000000000000000000000000000000000000..aee7a29019b9a6ba5c70f4ba878e192528e1a21a --- /dev/null +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference4.C @@ -0,0 +1,14 @@ +// { dg-do compile { target c++17 } } +// { dg-options "-Wdangling-reference" } +// Check that we warn here even without -Wsystem-headers. + +#include <optional> +#include <string> + +auto f() -> std::optional<std::string>; + +void +g () +{ + for (char c : f().value()) { (void) c; } // { dg-warning "dangling reference" } +}