0

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.

JWZ1996
  • 77
  • 9
  • Probably not as much faster as you would like. Reading from a file is sssssloooowwww, and if you gotta do it, ya gotta do it. Not sure what you need the `stringstream` for. Add the code for that, or ask another question about it, and there's good odds someone can give you a hand trimming it out. – user4581301 Nov 04 '19 at 16:20
  • Show your code which you want speed up then you will receive a feedback how this can be properly achieved. – Marek R Nov 04 '19 at 16:32
  • I cannot, because it does not exist yet. I heard that _substr_ method works faster, and i wanted to use it in CSV file read only. – JWZ1996 Nov 04 '19 at 16:57
  • You probably can map the file on memory using `mmap` (linux) or `virutal mapping `(win32) https://learn.microsoft.com/en-us/windows/win32/memory/file-mapping – Raxvan Nov 04 '19 at 17:55

2 Answers2

3

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • Thanks! I thought about string as a byte array for that represents the file. – JWZ1996 Nov 04 '19 at 16:56
  • @JWZ1996 Note that if you `mmap()` the file, you can construct a `std::string_view` directly against the memory-mapped region, as indicated in the other answer. (Boost is not required, but gives proper RAII to the mmap resource.) – cdhowie Nov 04 '19 at 17:47
  • @cdhowie i did not :), i removed it. – Raxvan Nov 04 '19 at 17:58
2

If you have access to boost, you can point a string view to the data() of a boost::iostreams::mapped_file.

Caleth
  • 52,200
  • 2
  • 44
  • 75