我知道一种从流中阅读并使用下面使用的方法:
strstream s; // It can be another standard stream type
// ...
while (!s.eof())
{
char buf[MAX];
s.read(buf, sizeof (buf));
int count = s.gcount();
THIRD_PARTY_FUNCTION(buf, count);
// ...
}
但是此代码有一个虐待点,它首先将数据从流到buf
复制,然后将buf
传递给THIRD_PARTY_FUNCTION
。
有什么方法可以将代码改革以下(我的意思是下面的代码避免了额外的副本)?
strstream s; // It can be another standard stream type
// ...
while (!s.eof())
{
char *buf = A_POINTER_TO_DATA_OF_STREAM(s);
int count = AVAIABLE_DATA_SIZE_OF_STREAM(s);
// Maybe it needs s.seekg(...) here
THIRD_PARTY_FUNCTION(buf, count);
// ...
}
类似的东西可能对您有用。
char buffer[2000];
std::istream& s = getStreamReference();
s.rdbuf()->pubsetbuf(buffer, 2000);
while(s)
{
THIRD_PARTY_FUNCTION(buffer, s.rdbuf()->in_avail());
s.ignore(s.rdbuf()->in_avail());
// Not sure this may go into an infinite loop.
// Its late here so I have not tested it.
}
请注意,请确保我关心复制2K缓冲区的成本。
分析必须表明,这是一个真正的热点,在我考虑进行这种优化之前,在性能上造成了重大降解。在这里99%的时间里,可读性将是我最重要的因素。
您可以通过首先调用其成员方法str以获取std :: string,然后调用其构件函数C_ST它可以到c风格的无效终止char []。