c++stlstring-view

File to std::string_view


Is it possible to load file directly into the std::string_view?

Directly = without creating the proxy std::string from stringstream.

It would make a lot of my code faster.


Solution

  • If I understand what you are asking, no.

    std::string_view refers to a region of memory, but it does not own that memory. This means that an std::string_view requires that another object exist which actually holds the char objects that it refers to.

    If an std::string_view is referring to an std::string and that string's lifetime ends, then the std::string_view is now effectively a dangling reference/pointer and trying to read characters from it would cause undefined behavior.

    Note that std::string_view can refer to contiguous sequences of char objects aside from std::string, such as a simple char array or an std::vector<char>, but regardless of what it refers to, the referent must exist at least as long as the std::string_view will be used.