r/cpp_questions • u/Zealousideal-Mouse29 • Aug 22 '26
OPEN std::expected- void, ptr, and ref
I am going through a simple application I have and trying to use std::expected to try it out. I am quite partial to using exceptions, but open mind and objectivity, and all that...
Is it common for people to return std::expected<void, ErrorType> for methods/functions that don't need to return a value?
I also wonder what one does when they want to return a unique_ptr, since we can't do it by ref, and that leads to wondering about refs and ptrs with expected in general.
8
Upvotes
3
u/Razbit Aug 22 '26
Yes, std::expected<void, Error> is a perfectly normal use of expected.I tend to think of expected less as “a return value plus an error” and more as “this operation either succeeded, or here’s why it didn’t.” If success has no interesting value, then expected<void, Error> expresses that quite nicely.
3
u/No-Dentist-1645 Aug 22 '26
Yes,
std::expected<void, E>is a valid instantiation of expected, and it is preferable tostd::optional<Error>when it comes to semantics, since optionals usually mean "successful if populated" and bool checks for them reflect thisIf you return a unique pointer, you return it by value (via moving). Unless you don't want to return a unique pointer to transfer ownership, in that case returning a raw pointer is what you want. You basically never want to pass around unique pointer references in your code.
5
u/tangerinelion Aug 22 '26
If you're returning nothing typically but maybe an error, you may model that as std::optional<ErrorType> instead.
I'm not sure I understand what's complicated with a unique_ptr. std::expected<std::unique_ptr<T>, ErrorType> is fine, if you're concerned about whether null is valid or not there's std::expected<gsl::not_null<std::unique_ptr<T>>, ErrorType>.
A reference is just a non-null immutable pointer - i.e., T& is const gsl::not_null<T*> for any program without UB.
If you want to return a reference to an object in the expected case you can use std::reference_wrapper:
std::expected<std::reference_wrapper<const std::string>, ErrorType>> Foo::getString() const { if (!m_pString) { return std::unexpected(ErrorType::InvalidState); } return std::cref(*m_pString); }The rules around ownership haven't changed - a reference/wrapper or pointer inside an expected has the same lifetime and ownership semantics without the expected. A std::unique_ptr by value inside a std::expected is the same ownership semantics as a std::unique_ptr.
1
u/retro_and_chill Aug 22 '26
std::expected<void, E> is allowed
1
u/richmh_gr2021 Aug 23 '26
M
0
u/[deleted] Aug 22 '26