std :: istringstream从std :: string不复制 [英] std::istringstream from std::string without copying

查看:166
本文介绍了std :: istringstream从std :: string不复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用这个:

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


我想避免不必要的复制,以提高性能,所以我尝试:

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

似乎做了这项工作)。我的问题是,这是安全给定的const_cast?
我的意思是,只要我使用istrinstream,内部缓冲区不应该被istringstream类写入,所以ss变量应该保持在一个有效的状态,只要行变量有效,

$ const_cast 是安全的,因为底层的 std :: string 的缓冲区不是 const 。是的,只要没有过期,而 ss 正在读取,你的程序应该是罚款。 / p>

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?

解决方案

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.

这篇关于std :: istringstream从std :: string不复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆