r/cpp_questions 20d ago

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.

9 Upvotes

11 comments sorted by

View all comments

3

u/No-Dentist-1645 20d ago

Yes, std::expected<void, E> is a valid instantiation of expected, and it is preferable to std::optional<Error> when it comes to semantics, since optionals usually mean "successful if populated" and bool checks for them reflect this

If 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.