c++stringc++17string-view

How you convert a std::string_view to a const char*?


Compiling with gcc-7.1 with the flag -std=c++17, the following program raises an error:

#include <string_view>
void foo(const char* cstr) {}
void bar(std::string_view str){
    foo(str);
}

The error message is

In function 'void bar(std::string_view)':
error: cannot convert 'std::string_view {aka std::basic_string_view<char>}' to 'const char*' for argument '1' to 'void foo(const char*)'
 foo(str);

I'm surprised there is no conversion to const char* because other libraries (abseil, bde), provide similar string_view classes which implicitly convert to const char*.


Solution

  • A std::string_view doesn't provide a conversion to a const char* because it doesn't store a null-terminated string. It stores a pointer to the first element, and the length of the string, basically. That means that you cannot pass it to a function expecting a null-terminated string, like foo (how else are you going to get the size?) that expects a const char*, and so it was decided that it wasn't worth it.

    If you know for sure that you have a null-terminated string in your view, you can use std::string_view::data.

    If you're not you should reconsider whether using a std::string_view in the first place is a good idea, since if you want a guaranteed null-terminated string std::string is what you want. For a one-liner you can use std::string(object).c_str() (note: the return value points to a temporary std::string instance that will get destroyed after the end of the expression!).