https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112480
--- Comment #2 from Corey Kosak <gnu at kosak dot com> ---
Thanks for the reply and the correction about illegally running the destructor.
As for why the compiler can't do the optimization itself, I don't know, but the
optimization isn't applied here either:
```
void func(bool &b) {
if (b) {
b = false;
}
}
```
However, it seems we can force the optimization to happen if we do the
assignment in both branches of the 'if', as in
```
void func(bool &b) {
if (b) {
b = false;
} else {
b = false;
}
}
```
...which suggests that a less Yuck-inducing diff might be
```
--- optional.ORIG 2023-11-10 21:37:00.623586305 +0000
+++ optional 2023-11-10 21:38:54.021199563 +0000
@@ -316,6 +316,8 @@
{
if (this->_M_engaged)
_M_destroy();
+ else
+ this->_M_engaged = false;
}
};
```
which produces the desired assembly, but at the cost of looking to the reader
like it's superfluous code.
...with the disclaimer that I don't understand why the "if
(!std::__is_constant_evaluated())" was necessary in your change, so I didn't
mention it here, so I could be missing something still.