I have a piece of C++20 code that I believe is valid, but our static analyzer thinks it's unsafe.
struct Foo {
explicit Foo() { activeFoo = this; }
~Foo() { activeFoo = nullptr; }
Foo(const Foo&) = delete;
Foo(Foo&&) = delete;
inline static const Foo* activeFoo = nullptr;
};
Foo makeFoo()
{
// Is there a dangling reference here?
return Foo();
}
int main()
{
auto myFoo = makeFoo();
}
My static analyzer thinks makeFoo
causes activeFoo
to point to a temporary object and will become a dangling pointer. I believe this is wrong; the return Foo();
should get a guaranteed copy elision (as evidenced by the deleted copy & move constructors), so there is only ever one Foo
instance constructed, myFoo
.
Who is correct?