[libcxx-commits] [libcxx] [libc++] Fix UB in <expected> related to "has value" flag (#68552) (PR #68733)

Jan Kokemüller via libcxx-commits libcxx-commits at lists.llvm.org
Mon Oct 30 03:24:35 PDT 2023


================
@@ -452,9 +412,10 @@ class expected {
       std::destroy_at(std::addressof(__union_.__val_));
     } else {
       std::destroy_at(std::addressof(__union_.__unex_));
-      __has_val_ = true;
     }
-    return *std::construct_at(std::addressof(__union_.__val_), __il, std::forward<_Args>(__args)...);
+    std::construct_at(std::addressof(__union_.__val_), __il, std::forward<_Args>(__args)...);
+    __has_val_ = true;
+    return *std::addressof(__union_.__val_);
   }
 
 
----------------
jiixyj wrote:

Alright, I added some tests for `swap()`. The only slightly tricky thing was to test those exception guards when rolling back a failed swap:

```c++
        auto __trans = std::__make_exception_guard([&] {
          std::construct_at(std::addressof(__with_err.__union_.__unex_), std::move(__tmp));
        });
```

There should really be a `__with_err.has_value = false` after the `std::construct_at`, but since the current data layout doesn't use `[[no_unique_address]]` anyway when the move constructors are not trivial, this would not make a difference right now.

https://github.com/llvm/llvm-project/pull/68733


More information about the libcxx-commits mailing list