In the article about std::expected, I introduced the type and showed some basic examples, and in this text, you’ll learn how it is implemented.

Understand internals of std::expected - C++ Stories

submited by
Style Pass
2024-04-30 14:30:07

In the article about std::expected, I introduced the type and showed some basic examples, and in this text, you’ll learn how it is implemented.

In short, std::expected should contain two data members: the actual expected value and the unexpected error object. So, in theory, we could use a simple structure:

However, std::variant does not provide some specific behaviors that std::expected might need, such as conditional explicit constructors and assignment operators based on the contained types’ properties. So, additional work would be required to implement these properly.

Furthermore, std::variant has to be very generic and offers a way to handle many alternative types in one object, which is “too much” for the expected type, which needs only two alternatives.

Here, _Value and _Unexpected are two data members that share the same memory location within an instance of expected. Which member of the union is currently active (i.e., contains valid data) is not tracked by the union itself. Therefore, the expected class maintains an additional boolean member, _Has_value, to track whether the union currently holds a _Ty value (_Has_value is true) or an _Err error (_Has_value is false).

Leave a Comment
Related Posts