llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[libc++] `optional<T&>` is a structural type

Open frederick-vs-ja opened this issue 3 months ago • 2 comments

Currently, the internal pointer in libc++'s optional<T&> is a public member, which makes optional<T&> a structural type. As a result, the following code snippet is well-formed when using libc++, which doesn't seem intended. Godbolt link.

#include <optional>
#include <utility>

inline constexpr int num = 42;

void test() {
  (void)std::cw<std::optional<const int&>{num}>;
}

This is possibly a bug as [objects.within.classes]/3 requires "equivalent observable behavior", while currently a private data member certainly makes the class non-structural.

However, it seems desired making optional a structural type (see P2484 and P3380), and when optional<T&> is guaranteed to be a structural type, the intended behavior is probably equivalent to having a public pointer member, which is what libc++ currently does.

Do we want to keep the status quo (i.e. keeping the member public) and document this as an extension, or make the member private?

CC @smallp-o-p @ldionne @philnik777.

frederick-vs-ja avatar Aug 10 '26 06:08 frederick-vs-ja

IMO we should make it private. I don't think it's worth having an extension here, especially since this is a quite niche use-case.

philnik777 avatar Aug 10 '26 08:08 philnik777

Whoops. Overlooked that.

smallp-o-p avatar Aug 10 '26 12:08 smallp-o-p