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

            Bug ID: 118670
           Summary: -Wdangling-reference false positive when returning a
                    reference from a reference_wrapper
           Product: gcc
           Version: 15.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: llvm at rifkin dot dev
  Target Milestone: ---

Gcc diagnoses the following as a possibly-dangling reference:

#include <string>
#include <functional>

class R {
    std::reference_wrapper<const std::string> v;
public:
    R(std::string& u) : v(u) {}

    const std::string& value() {
        return v;
    }
};

std::string x;

R get_str() {
    return x;
}

void foo() {
    const auto& str = get_str().value();
}


<source>: In function 'void foo()':
<source>:21:17: warning: possibly dangling reference to a temporary
[-Wdangling-reference]
   21 |     const auto& str = get_str().value();
      |                 ^~~
<source>:21:38: note: the temporary was destroyed at the end of the full
expression 'get_str().R::value()'
   21 |     const auto& str = get_str().value();
      |                       ~~~~~~~~~~~~~~~^~
<source>:21:17: warning: unused variable 'str' [-Wunused-variable]
   21 |     const auto& str = get_str().value();
      |                 ^~~
Compiler returned: 0

https://godbolt.org/z/6qc7697G3

If I change `std::reference_wrapper<const std::string> v;` to `const
std::string& v;` there's no warning.

Reply via email to