https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121122
Bug ID: 121122
Summary: -Wdangling-reference false postitive when adding a
non-dangling reference to the mix
Product: gcc
Version: 16.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: b.stanimirov at abv dot bg
Target Milestone: ---
I reproduce this without fail on gcc 13 to trunk (as of this post)
This code expectedly produces no warnings:
```
struct vec { int x, y; };
struct generator {
const vec a;
generator(const vec& a)
: a(a)
{}
struct iterator {
const vec a;
int i;
iterator(const vec& a) : a(a) {
i = a.x;
}
iterator& operator++() {
++i;
return *this;
}
int operator*() const {
return i;
}
bool operator==(const iterator& b) const { return i == b.i; }
bool operator!=(const iterator& b) const { return i != b.i; }
};
iterator begin() const { return {a}; }
iterator end() const { return {vec{a.y, a.y}}; }
};
generator generate(const vec& v) {
return {v};
}
int loop() {
int sum = 0;
for (auto i : generate({1, 2})) {
sum += i;
}
return sum;
}
```
Compiler explorer: https://godbolt.org/z/xf1P5ecWj
I then add another reference to the mix, which is most definitely not dangling
(even less dangling than the already-not-dangling temporary):
```
struct vec { int x, y; };
struct generator {
const vec& ref; // HERE!!!!!
const vec a;
generator(const vec& ref, const vec& a)
: ref(ref) // HERE!!!!!
, a(a)
{}
struct iterator {
const vec a;
int i;
iterator(const vec& a) : a(a) {
i = a.x;
}
iterator& operator++() {
++i;
return *this;
}
int operator*() const {
return i;
}
bool operator==(const iterator& b) const { return i == b.i; }
bool operator!=(const iterator& b) const { return i != b.i; }
};
iterator begin() const { return {a}; }
iterator end() const { return {vec{a.y, a.y}}; }
};
generator generate(const vec& r, const vec& v) {
return {r, v};
}
int loop() {
const vec vv = {0, 0}; // HERE!!!!!
int sum = 0;
for (auto i : generate(vv, {1, 2})) {
sum += i;
}
return sum;
}
```
And I get -Wdangling-reference
Compiler explorer with bug: https://godbolt.org/z/6Gsxj5xcr