std::istringstream from std::string without copying

丶灬走出姿态 提交于 2019-12-07 07:38:53

问题


I've been using this:

ifstream in("file.txt")
string line;    
getline(in,line);
istringstream iss(line);
...

for some simple parsing. I would like to avoid unnecessary copying in order to improve performance so I tried:

ifstream in("huge_line.txt");
string line;
getline(in,line);
istringstream ss;
ss.rdbuf()->pubsetbuf(const_cast<char*>(line.c_str()), line.size());
...

and it seems to do the job (significantly improve performance, that is). My question is, is this safe given the const_cast? I mean, as long as I'm working with an istrinstream, the internal buffer should never get written to by the istringstream class, so the ss variable should remain in a valid state as long as the line variable is valid and unchanged, right?


回答1:


The const_cast is safe, because the underlying buffer of std::string is not const. And yes, as long as line does not expire while ss is being read from, your program should be fine.




回答2:


The effect of ss.rdbuf()->pubsetbuf is implementation-defined and hence doesn't necessarily do what you expect.

So, the effect of your altered code doesn't need to be equivalent to the initial one.



来源:https://stackoverflow.com/questions/16875321/stdistringstream-from-stdstring-without-copying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!