r/cpp • • Apr 24 '23

The View of The String

https://cppsenioreas.wordpress.com/2023/04/24/the-view-of-the-string/

std::string_view can optimize both performance and code readability in code sections which handle strings. However it can also lead to UB and to memory issues if used incorrectly.

0 Upvotes

13 comments sorted by

View all comments

20

u/IyeOnline Apr 24 '23

Rule #1: Never return a std::string_view

I disagree with the conclusion in the last paragraph here.

Returning a std::string_view is no different than returning a reference from other functions. If you saw your logic here through to the end, then operator[] or any getterse should not return references either.

1

u/arka2947 Apr 24 '23 edited Apr 25 '23

Modern Cpp encourages the use of auto, consider:

auto var = thing.get()

If ret val is std::string this is safe, if string_view, possible foot gun.

Sadly i agree with the dont return string_view opinion.

1

u/tisti Apr 25 '23
auto var = std::string{thing.get()}

This nicely follows the DRY principle as well.

2

u/Fulgen301 Apr 25 '23

What's wrong with std::string var{thing.get()}?

1

u/tisti Apr 26 '23

Same thing, so it comes down to personal preference.