https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87582

            Bug ID: 87582
           Summary: Returning a reference to a data member via structured
                    bindings incorrectly reports dangling
           Product: gcc
           Version: 8.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: cfretz at icloud dot com
  Target Milestone: ---

My apologies if I've misunderstood something, or if I've duplicated an issue
someone else already posted, but I ran into this late last night:

struct custom {
  int one, two;
};

custom thing {1, 2};

auto& bad() {
  auto& [one, two] = thing;
  return one;
}

int main() {
  [[maybe_unused]] auto& one = bad();
}

All versions of gcc I was able to test on godbolt reported returning a
reference to a local variable in the function "bad", while no versions of clang
reported the same.
For reference: https://godbolt.org/z/fcNZDb

To my knowledge, this code should have the end result of binding the reference
"one" in main to the first data member of the global "thing"; not returning a
reference to a local in the function "bad".

The warning is also not issued if "thing" is a std::tuple<int, int>, or if the
type "custom" is made to be a "tuple-like type" by specializing
std::tuple_size, std::tuple_element, etc.

I was originally expecting that this was an error somewhere in static analysis,
but if you go on to actually try to use the reference you get a segfault as in
this program: https://godbolt.org/z/lb1afO. Address-sanitizer reports a
null-pointer dereference.

Let me know if any clarifications are required, and I hope I haven't wasted
anyone's time!

Reply via email to