Skip to content

Avoid -Wdangling-reference false positives in locale helpers - #4876

Open
viordash wants to merge 1 commit into
fmtlib:mainfrom
viordash:fix-dangling-reference-locale-facets
Open

Avoid -Wdangling-reference false positives in locale helpers#4876
viordash wants to merge 1 commit into
fmtlib:mainfrom
viordash:fix-dangling-reference-locale-facets

Conversation

@viordash

@viordash viordash commented Aug 2, 2026

Copy link
Copy Markdown

GCC 13/14 warns in two locale helpers when a precompiled header is used:

include/fmt/format-inl.h:132: warning: possibly dangling reference to a temporary
  [-Wdangling-reference]
include/fmt/xchar.h:49: same

It is a false positive: locale_ref::get<std::locale>() returns a copy, and the
reference returned by std::use_facet stays valid as long as any copy of that locale
exists. GCC only warns when the declaration comes from a precompiled header; with
<locale> included normally it stays quiet. Reproducible with plain <locale>,
no fmt involved:

// t.cpp
#include <locale>
template <typename Char> auto f(const std::locale& l) -> Char {
  auto&& facet = std::use_facet<std::numpunct<Char>>(std::locale(l));
  return facet.decimal_point();
}
template char f<char>(const std::locale&);

// pch.h
#include <locale>

g++ -Wdangling-reference -c t.cpp                    # quiet
g++ -x c++-header pch.h -o pch.h.gch
g++ -Wdangling-reference -include pch.h -c t.cpp     # warns

(GCC 13.4; -Wdangling-reference comes with -Wextra there)

This patch binds the locale copy to a named variable at both call sites, so no reference
is bound to a temporary. Same single copy, no behaviour change, and the lifetime becomes
explicit instead of relying on the "valid while any copy exists" guarantee.

Checked with GCC 13.4: warnings gone when a PCH is in use, ctest passes 21/21, and
locale-aware output is unchanged

Originally filed against spdlog, which vendors these files (gabime/spdlog#3638), and
closed there with a pointer to this repository.

@viordash
viordash requested a review from vitaut as a code owner August 2, 2026 09:31
@vitaut

vitaut commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Could you provide a godbolt CMake-project (since it requires PCH) repro?

@viordash

viordash commented Aug 2, 2026

Copy link
Copy Markdown
Author

Here is a CMake project repro: https://godbolt.org/z/vfcfWThT7

/opt/compiler-explorer/libs/fmt/trunk/include/fmt/format-inl.h:132:10: warning:
  possibly dangling reference to a temporary [-Wdangling-reference]

Removing the target_precompile_headers() line makes it quiet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants