Search code examples
c++c++17string-view

What should be the semantics of a reference to const string in C++17?


There are several ways to pass textual information into a function in C++: that could be a c-string/std::string, by value/by reference, lvalue/rvalue, const/mutable. C++17 adds a new class into the standard library: std::string_view. The semantics of the string_view is to provide read-only textual information without ownership. So if you need just to read a string you may use:

void read(const char*);        // if you need that in a c-style function or you don't care of the size
void read(const std::string&); // if you read the string without modification in C++98 - C++14
void read(std::string_view);   // if you read the string without modification in C++17

My question is if there any case when void read(const std::string&) should be preferred to void read(std::string_view) in C++17. Assume that backward compatibility is not needed.


Solution

  • Do you need null-termination? If so, you have to use one of these:

    // by convention: null-terminated
    void read(const char*);
    
    // type invariant: null-terminated
    void read(std::string const&);
    

    Because std::string_view is just any contiguous range of char const, there is no guarantee that it is null-terminated, and it's undefined behavior to try to peek past the last character.

    If you do not need null-termination, but need to take ownership of data, do this:

    void read(std::string );
    

    If you need neither null-termination nor ownership nor modification of data, then yeah your best bet is:

    void read(std::string_view );