https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121871
Bug ID: 121871
Summary: False positive -Wdangling-reference for static classes
Product: gcc
Version: 15.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: martin at martin dot st
Target Milestone: ---
The following gives IMO false positive -Wdangling-reference warnings, with GCC
13.1 - 15.2:
---
#include <string>
class MyClass {
public:
static const int &getRef(std::string a);
};
void func(std::string a) {
const int &ref = MyClass::getRef(a);
(void)ref;
}
---
$ g++ -c static-reference.cpp -Wall -Wextra
static-reference.cpp: In function ‘void func(std::string)’:
static-reference.cpp:9:16: warning: possibly dangling reference to a temporary
-Wdangling-reference]
9 | const int &ref = MyClass::getRef(a);
| ^~~
static-reference.cpp:9:37: note: the temporary was destroyed at the end of the
full expression ‘MyClass::getRef(std::__cxx11::basic_string<char>(a))’
9 | const int &ref = MyClass::getRef(a);
| ~~~~~~~~~~~~~~~^~~
---
If the getRef method is a non-static method, or if it doesn't take a temporary
std::string as argument, there's no warning.
Admittedly, there is a temporary involved in the argument of the method, but
there's nothing that implies that this temporary is related to the reference
that is returned.