2

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.

4
  • 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. Commented Nov 4, 2019 at 16:20
  • Show your code which you want speed up then you will receive a feedback how this can be properly achieved. Commented Nov 4, 2019 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. Commented Nov 4, 2019 at 16:57
  • You probably can map the file on memory using mmap (linux) or virutal mapping (win32) learn.microsoft.com/en-us/windows/win32/memory/file-mapping Commented Nov 4, 2019 at 17:55

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I thought about string as a byte array for that represents the file.
@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 i did not :), i removed it.
2

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

1 Comment

@Raxvan those are platform dependant
0

It is actually quite easy with C++20 and std::ostringstream::view:

std::ifstream file {file_path};
std::ostringstream oss {};
oss << file.rdbuf();
// Use std::ostringstream::view to avoid a string copy
// But remember that std::string_view does not own the memory!
my_function(oss.view());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.