https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111299
Bug ID: 111299 Summary: lack of warning on dangling reference to temporary Product: gcc Version: 13.1.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: barry.revzin at gmail dot com Target Milestone: --- Consider the following reduced example: using size_t = decltype(sizeof(0)); template <typename T, size_t N> struct array { T elems[N]; auto data() -> T* { return elems; } auto data() const -> T const* { return elems; } auto size() const -> size_t { return N; } }; template <typename T> struct Span { T* p; size_t len; Span(T* p, size_t len) : p(p), len(len) { } template <typename R> Span(R&& r) : p(r.data()), len(r.size()) { } }; struct [[gnu::packed]] X { array<int, 1> value; }; auto get_slice_ref(X const& x) { return Span<int const>(x.value); } auto get_slice_ptr(X const& x) { return Span<int const>(x.value.data(), 1); } Span<T> is a heavily reduced version of std::span: no fixed extent, no constraints, etc. X is a packed struct with a single array member. Neither version (get_slice_ptr or get_slice_ref) emits any warnings on gcc, with -Wall -Wextra -Wdangling-reference. But the -DREF version is horribly broken. What ends up happening is that in order to bind x.value to the reference parameter R&& r, we can't actually do that, so instead we create a temporary initialized by copying x.value and we bind a reference to that temporary, returning a Span pointing to... that. Which immediately goes out of scope and we end up with a dangling Span. You can see the broken-ness in the codegen (https://godbolt.org/z/zY77eresb). The pointer version does the right thing: get_slice_ptr(X const&): mov rax, rdi mov edx, 1 ret The ref version gives me some garbage: get_slice_ref(X const&): lea rax, [rsp-12] mov edx, 1 ret It would be really helpful if I had any indication that something is going wrong here.