非复制istringstream [英] non-copying istringstream
问题描述
因此 istringstream
在初始化时复制字符串的内容,例如
So istringstream
copies the contents of a string when initialised, e.g
string moo("one two three four");
istringstream iss(moo.c_str());
我想知道是否有一种方法使 std :: istringstream
使用给定的
c_str
作为其缓冲区而不复制任何东西。这样,在将 std :: istringstream&
传递给需要 istream& $的函数之前,不必复制大量内存c $ c>作为参数。
I was wondering if there's a way to make std::istringstream
use the given c_str
as its buffer without copying things. This way, it won't have to copy large bits of memory before passing the std::istringstream&
to functions that take istream&
as an argument.
我一直想做的是转换一些函数,只需要 std :: ifstream& / code>参数(它们大多是解析器)转换为采用
istream&
。
What I've been trying to do is convert some functions which only take std::ifstream&
arguments (they're mostly parsers) into taking istream&
as well. Would I have to make my own istream
subclass for this?
推荐答案
我需要为自己创建 istream
编写从给定内存区域读取的基本 std :: streambuf
类是相当微不足道的。然后,您可以从中构造一个 istream
,并从中读取。
It's fairly trivial to write a basic std::streambuf
class that reads from a given memory area. You can then construct an istream
from this and read from that.
请注意,缓冲区的生命周期指向 c_str code>是非常有限,虽然,并不能保证调用
c_str()
想要导致一些复制,虽然我不知道任何实现
Note that the lifetime of the buffer pointed to be c_str()
is very limited, though, and there's no guarantee that a call to c_str()
want cause some copying although I don't know of any implementations where it does.
这篇关于非复制istringstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!