[libcxx-commits] [libcxx] [libc++] Correct `optional<T&>` implementation (PR #174537)

William Tran-Viet via libcxx-commits libcxx-commits at lists.llvm.org
Wed Jan 7 11:15:40 PST 2026


================
@@ -149,9 +149,48 @@ void test_explicit() {
 #endif
 }
 
+#if TEST_STD_VER >= 26
+struct Throws {
+  int val = 42;
+  bool b  = false;
+  constexpr Throws() {};
+  operator int&() {
+    if (b) {
+      TEST_THROW(1);
+    }
+    return val;
+  }
+};
+
+constexpr bool test_ref() {
+  {
+    int i = 0;
+    std::optional<int&> o(i);
+    ASSERT_NOEXCEPT(std::optional<int&>(i));
+    assert(o.has_value());
+    assert(&(*o) == &i);
+    assert(*o == 0);
+    assert(o.value() == 0);
+  }
+
+#  ifndef TEST_HAS_NO_EXCEPTIONS
+  {
+    using T = Throws;
+    T t{};
+    ASSERT_NOT_NOEXCEPT(std::optional<int&>(t));
+    // TODO: There doesn't seem to be a usable type which can actually make the ctor not noexcept
----------------
smallp-o-p wrote:

What I meant is that I couldn't actually figure out a type that when actually used to construct an `optional<T&>`, would compile, and cause it to potentially throw an exception.

Best I could do was that deranged `operator int&()` example but it actually fails compilation if I try to instantiate it.

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


More information about the libcxx-commits mailing list