Synopsis: | Use string_view correctly |
Language: | C++ |
Severity Level: | 5 |
Category: | Parts of C++ to Avoid |
Description: |
C++17 brings us std::string_view. It is a really useful tool: If you want to write a function accepting some string, but does not need ownership, i.e. a view, use std::string_view. It supports both const char* and std::string without any work, and does not involve any heap allocations. Further, it clearly signals intent: this function takes a view. It doesn't own anything, it just views it. Yet there is one design decisions that warrants a discussion: std::string_view silently views temporaries as well. This can create a problem if the view lives longer than the temporary, as the view now views already destroyed data. Check the following code: std::string_view get_str() const { // substr starting at index 1 till the end return my_str_.substr(1u); } The problem is that std::string::substr() - which is being called here, returns std::string; a temporary std::string. So we're creating a view to a temporary object which will blow up as soon as we try to use it. Be careful when using std::string_view in return values. Ensure that the function doesn't return a temporary. Be careful when calling std::string::substr(). Be very careful when storing a std::string_view somewhere, i.e. in a class object. Ensure that the viewed string outlives the view. |
Literature References: |
foonathan::​blog() |