[libcxx-commits] [libcxx] [libc++] Correct `optional<T&>` implementation (PR #174537)
William Tran-Viet via libcxx-commits
libcxx-commits at lists.llvm.org
Thu Jan 8 09:25:20 PST 2026
================
@@ -496,29 +491,33 @@ struct __optional_storage_base<_Tp, true> {
_LIBCPP_HIDE_FROM_ABI constexpr __optional_storage_base() noexcept : __value_(nullptr) {}
+ template <class _Up>
+ _LIBCPP_HIDE_FROM_ABI constexpr void __convert_init_ref_val(_Up&& __val) {
+ _Tp& __r(std::forward<_Up>(__val));
+ __value_ = std::addressof(__r);
+ }
+
template <class _UArg>
- _LIBCPP_HIDE_FROM_ABI constexpr explicit __optional_storage_base(in_place_t, _UArg&& __uarg)
- : __value_(std::addressof(__uarg)) {
+ _LIBCPP_HIDE_FROM_ABI constexpr explicit __optional_storage_base(in_place_t, _UArg&& __uarg) {
static_assert(!__reference_constructs_from_temporary_v<_Tp, _UArg>,
"Attempted to construct a reference element in optional from a "
"possible temporary");
+ __convert_init_ref_val(__uarg);
}
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void reset() noexcept { __value_ = nullptr; }
[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool has_value() const noexcept { return __value_ != nullptr; }
- _LIBCPP_HIDE_FROM_ABI constexpr value_type& __get() const& noexcept { return *__value_; }
-
- _LIBCPP_HIDE_FROM_ABI constexpr value_type&& __get() const&& noexcept { return std::forward<value_type>(*__value_); }
+ _LIBCPP_HIDE_FROM_ABI constexpr value_type& __get() const noexcept { return *__value_; }
template <class _UArg>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void __construct(_UArg&& __val) {
_LIBCPP_ASSERT_INTERNAL(!has_value(), "__construct called for engaged __optional_storage");
static_assert(!__reference_constructs_from_temporary_v<_Tp, _UArg>,
"Attempted to construct a reference element in tuple from a "
"possible temporary");
- __value_ = std::addressof(__val);
+ __convert_init_ref_val(__val);
----------------
smallp-o-p wrote:
Hm, maybe it would be simpler to review if I broke out the `optional<T&>` tests into their own directory...
https://github.com/llvm/llvm-project/pull/174537
More information about the libcxx-commits
mailing list