https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109945
--- Comment #25 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to Andrew Pinski from comment #9)
> struct Widget {
> int i;
> int a[4];
> };
> Widget *global = 0;
> Widget make2() { Widget w; w.i = 1; global = &w; return w; }
> void g() { global->i = 42; }
> int main() {
> Widget w = make2();
> int i = w.i;
> g();
> return (i == w.i);
> // Does this need to be reloaded and
> // compared? or is it obviously true?
> }
> ```
>
> But does w go out of the scope at the end of make2?
Yes. This example has undefined behaviour in all versions of C++.
w is a local variable, its lifetime is the function body of make2, and global
becomes an invalid pointer after make2 returns, so dereferencing global in g()
is UB.
> Similar question to make
> in the original testcase, does the temp go out of scope?
Before C++17 yes, it was undefined for exactly the same reasons.
That changed in C++17 and now a temporary is not "materialized" until as late
as possible. In many cases there would be no temporary, the prvalue returned by
make() would initialize w in main without any intermediate temporary.
However, [class.temporary] p3 explicitly allows the compiler to create a
temporary object when returning a class with a trivial copy constructor and
trivial (or deleted) destructor. This is permitted precisely to allow what the
x86_64 ABI requires: the return value is passed in registers. Completely
eliding the creation and copy of a temporary would have required an ABI break.
So the example in comment 0 is also an incorrect program, even in C++17. It's
unspecified whether the prvalue created in make() is only materialized when
constructing w (so there is never any temporary Widget) or whether the prvalue
is materialized to a temporary which then gets copied to w using the trivial
copy constructor.
Since it's unspecified, the program cannot rely on any particular behaviour.
The 'global' pointer might point to w, or it might point to a temporary which
has gone out of scope, and in the latter case, dereferencing it in g() is UB.
So inconsistent behaviour with different optimization settings and/or noipa
attributes seems fine. Either global == &w or the program has UB.
I think this is INVALID.