[libcxx-commits] [libcxx] [libc++] Implement P2988R12: `std::optional<T&>` (PR #155202)

Adrian Vogelsgesang via libcxx-commits libcxx-commits at lists.llvm.org
Thu Sep 25 18:01:42 PDT 2025


vogelsgesang wrote:

afaict, the physical layout representation of a an `optional<Foo&>` would be

```cpp
struct OptionalFooRef {
  union {
    char __null_state_;
    Foo& __val_;
  };
  bool __engaged_;
};
```

I think a more optimal representation would be

```cpp
struct OptionalFooRef {
  // nullopt encoded as nullptr, since `nullptr` is not a valid reference
  Foo* __val_;
};
```

This would allow me to use `optional<Foo&>` as a more type-safe replacement for `Foo*` _without any performance penalties_.

Given that `optional<Foo&>` was previously forbidden, this wouldn't be an ABI break. However, if we would merge your PR as is, we could no longer do that optimization later on.

(Please note that I am not a contributor / reviewer for libc++. So please wait for feedback from others before acting on my comment. Not sure if I might be sending you into the wrong direction here 🙂)

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


More information about the libcxx-commits mailing list