为什么 std::optional<bool> 使用两个字节?

Dan*_* V. 1 c++ memory stl

如果 C++ 允许bool使用任何位,是什么阻止 C++ 优化std::optional使用 1 个字节并使用两个位来表示has_valuevalue()?当然,我们会使用掩码,但在现代处理器中它不会损害性能。

bol*_*lov 5

这个:

constexpr const T& operator*() const&;
constexpr T& operator*() &;
constexpr T&& operator*() &&;
Run Code Online (Sandbox Code Playgroud)

让你想要的变得不可能。operator*需要返回对持有对象的引用。