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

            Bug ID: 116360
           Summary: GCC gives false positive dangling reference for static
                    local variable
           Product: gcc
           Version: 15.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jlame646 at gmail dot com
  Target Milestone: ---

The following program produces false positive with static variable.
https://godbolt.org/z/P1G8YMvfK

```
# include <iostream>

std::string create_default_x() noexcept
{
    std::string default_x = "hello world";
    return default_x;
}

std::string const& get_x(std::string const& force_x = "") noexcept;

int main()
{
    std::string const& x = get_x();
    std::cout << x << std::endl;

    return 0;
}

std::string const& get_x(std::string const& force_x) noexcept
{
    static std::string x = (force_x.empty() ? create_default_x() :
std::string());
    if(!force_x.empty())
        x = force_x;
    return x;
}

```

GCC says:

```
 warning: possibly dangling reference to a temporary [-Wdangling-reference]
   13 |     std::string const& x = get_x();
      |                        ^
<source>:13:33: note: the temporary was destroyed at the end of the full
expression 'get_x(std::__cxx11::basic_string<char>(((const char*)""),
std::allocator<char>()))'
   13 |     std::string const& x = get_x();
      |                            ~~~~~^~
ASM generation compiler returned: 0
<source>: In function 'int main()':
<source>:13:24: warning: possibly dangling reference to a temporary
[-Wdangling-reference]
   13 |     std::string const& x = get_x();
      |                        ^
<source>:13:33: note: the temporary was destroyed at the end of the full
expression 'get_x(std::__cxx11::basic_string<char>(((const char*)""),
std::allocator<char>()))'
   13 |     std::string const& x = get_x();
```

We can use `-Wno-dangling-reference` to supress this.

Reply via email to