https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111607
Bug ID: 111607
Summary: False positive -Wdangling-reference
Product: gcc
Version: 14.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: fiesh at zefix dot tv
Target Milestone: ---
The following code triggers a `-Wdangling-reference` warning:
t.cpp: In function ‘consteval auto f(const V&)’:
t.cpp:19:22: warning: possibly dangling reference to a temporary
[-Wdangling-reference]
19 | auto const & s = std::visit([](auto const & v) -> S const & {
return v.s; }, v);
| ^
t.cpp:19:36: note: the temporary was destroyed at the end of the full
expression ‘std::visit<f(const V&)::<lambda(const auto:31&)>, const
variant<A>&>(<lambda closure object>f(const V&)::<lambda(const auto:31&)>(), (*
& v))’
19 | auto const & s = std::visit([](auto const & v) -> S const & {
return v.s; }, v);
|
~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <variant>
struct S {
constexpr S(int i_) : i(i_) {}
S(S const &) = delete;
S & operator=(S const &) = delete;
S(S &&) = delete;
S & operator=(S &&) = delete;
int i;
};
struct A {
S s{0};
};
using V = std::variant<A>;
consteval auto f(V const & v) {
auto const & s = std::visit([](auto const & v) -> S const & { return
v.s; }, v);
return s.i;
}
int main() {
constexpr V a{std::in_place_type<A>};
constexpr auto i = f(a);
return i;
}
It makes sure the warning is wrong though by
* having S be non-copyable
* evaluating everything at compile time where UB is not allowed to happen