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

前端 未结 3 686
误落风尘
误落风尘 2021-01-03 18:04

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

#include 
void foo(const char* cstr)          


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-03 18:47

    Simply do a std::string(string_view_object).c_str() to get a guaranteed null-terminated temporary copy (and clean it up at the end of the line).

    This is required because string view doesn't guarantee null termination. You can have a view into the middle of a longer buffer, for example.

    If this use case is expensive and you have proven it to be a bottleNeck, you can write an augmented string_view that tracks if it is null terminated (basically, if it was constructed from a raw char const*).

    Then you can write a helper type that takes this augmented string_view and either copies it to a std::string or stores the augmented string_view directly, and has an implicit cast-to-char const* that returns the properly null-terminated buffer.

    Then use that augmented helper type everywhere in your code base instead of string_view, possibly augmenting string view interaction with std string as well to catch the cases where you have a view that goes to the end of the std string buffer.

    But really, that is probably overkill.

    A better approach is probably rewriting the APIs that take const char* to take string_view.

提交回复
热议问题