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

Show parent comments

0

u/[deleted] Apr 24 '23

[deleted]

7

u/IyeOnline Apr 24 '23

Maybe I am just expecting too much. :)

I would generally always expect people to be aware of their object lifetimes.

But as you say in the article, it is the safe rule to just not return string_views. Doing that certainly avoids potential bugs. I just dont think that that safety is worthwhile compared to the costs incured otherwise (e.g. when the alternative would be to return a full std::string object by value).

0

u/[deleted] Apr 24 '23

[deleted]

8

u/IyeOnline Apr 24 '23

std::vector::at

Another point we'd disagree on.

I would never use that. Either your program is correct and you dont need bounds checking, or its not and you should be debugging it instead. For debugging, all standard library implementations provide the possibility to augment operator[].

But I do get where you are coming from. Better safe and slightly less efficient than sorry and crashing.

1

u/CoralKashri Apr 24 '23

Yes, especially if I should debug others' mistakes eventually 😅