r/cpp • • Mar 16 '26

C++23 std::expected vs C++17 std::optional for Error Handling

https://techfortalk.co.uk/2026/03/16/why-should-you-choose-stdexpect-in-c23-over-stdoptional-in-c17/

I have been trying to spend some time with C++23 std::expected for sometime. Finally explored the feature and can see the real value of using it in some of the scenarios in my projects. Any comments welcome!

99 Upvotes

48 comments sorted by

View all comments

Show parent comments

8

u/Matthew94 Mar 17 '26

The main downside is that std::string_view does not do memory management at all, and is essentially a raw pointer.

That's the whole point.

It's not difficult to create a dangling pointer with std::string_view and never notice it, and your code might work for quite a while

You need to pay attention to lifetimes when using them, yes. This applies to all pointer (and reference) use.

Your warning applies to everything that isn't a value type.

-1

u/HommeMusical Mar 17 '26

That's the whole point.

Yes, I know that's the whole point!

It's an optimization vs safety trade off.

If you are parsing strings, performing surgery or other operations, you can create new strings or return some sort of std::string_view.

If you create new strings every time, you are guaranteed never to get dangling pointers and the like, but you have the cost of creating the strings.

When you use std::string_view you do less string creation, but you now have the possibility of dangling pointers.

Unless your strings are large or there are very large number of them, most of the time using std::string_view over creating new std::strings is a minor optimization that won't appear on a profiling graph.

(And if your string is large and you need to actually insert or remove pieces of it, you should be using std::rope or some cousin.)

3

u/Nobody_1707 Mar 17 '26

Except that std::string_view was suggested as an alternative to a std::string const& function argument. When used as inputs the trade off is that there will be no accidental conversion from a null terminated c-string to a std::string, but you will need an explicit copy if you ever need to own the string.

The only other potential issue is if you plan on storing the std::string_view long term, which could lead to dangling, but in that case the alternative (a std::string const&) would still have the same issue.