此处的用法与
Using read() directly into a C++ std:vector相同,但具有重新分配的数量.
输入文件的大小未知,因此当文件大小超过缓冲区大小时,通过加倍大小来重新分配缓冲区.这是我的代码:
#include
#include
#include
int main()
{
const size_t initSize = 1;
std::vector buf(initSize); // sizes buf to initSize,so &buf[0] below is valid
std::ifstream ifile("D:\\Pictures\\input.jpg",std::ios_base::in|std::ios_base::binary);
if (ifile)
{
size_t bufLen = 0;
for (buf.reserve(1024); !ifile.eof(); buf.reserve(buf.capacity() << 1))
{
std::cout << buf.capacity() << std::endl;
ifile.read(&buf[0] + bufLen,buf.capacity() - bufLen);
bufLen += ifile.gcount();
}
std::ofstream ofile("rebuild.jpg",std::ios_base::out|std::ios_base::binary);
if (ofile)
{
ofile.write(&buf[0],bufLen);
}
}
}
程序按照预期打印矢量容量,并将输出文件写入与输入BUT相同的大小,在偏移initSize之前只输入与输入相同的字节,之后全部为零…
在read()中使用& buf [bufLen]肯定是一个未定义的行为,但& buf [0] bufLen得到了正确的写入,因为连续分配是有保证的,不是吗? (提供了initSize!= 0.注意std :: vector< char> buf(initSize);将buf的大小调整为initSize.是的,如果initSize == 0,在我的环境中发生朗姆酒致命错误.)我是否会错过什么?这也是UB吗?标准是否说明了std :: vector的这种用法?
PS:是的,我知道我们可以先计算文件大小并分配完全相同的缓冲区大小,但在我的项目中,可以预期输入文件几乎总是小于某个SIZE,所以我可以将initSize设置为SIZE并且期望没有开销(比如文件大小计算),并且仅为“异常处理”使用重新分配.是的,我知道我可以用resize()和capacity()替换reserve()和size(),然后用很少的开销来工作(每次调整大小都是零缓冲区),但是我仍然希望摆脱任何redundent操作,只是一种偏执……
更新1:
事实上,我们可以从标准中推断& buf [0] bufLen得到正确的帖子,考虑:
std::vector buf(128);
buf.reserve(512);
char* bufPtr0 = &buf[0],*bufPtrOutofRange = &buf[0] + 200;
buf.resize(256); std::cout << "standard guarantees no reallocation" << std::endl;
char* bufPtr1 = &buf[0],*bufInRange = &buf[200];
if (bufPtr0 == bufPtr1)
std::cout << "so bufPtr0 == bufPtr1" << std::endl;
std::cout << "and 200 < buf.size(),standard guarantees bufInRange == bufPtr1 + 200" << std::endl;
if (bufInRange == bufPtrOutofRange)
std::cout << "finally we have: bufInRange == bufPtrOutofRange" << std::endl;
standard guarantees no reallocation
so bufPtr0 == bufPtr1
and 200 < buf.size(),standard guarantees bufInRange == bufPtr1 + 200
finally we have: bufInRange == bufPtrOutofRange
并且这里可以用每个buf.size()< = i
const size_t initSize = 32;
std::vector buf(initSize);
buf.reserve(1024*100); // reserve enough space for file reading
std::ifstream ifile("D:\\Pictures\\input.jpg",std::ios_base::in|std::ios_base::binary);
if (ifile)
{
ifile.read(&buf[0],buf.capacity()); // ok. the whole file is read into buf
std::ofstream ofile("rebuld.jpg",std::ios_base::out|std::ios_base::binary);
if (ofile)
{
ofile.write(&buf[0],ifile.gcount()); // rebuld.jpg just identical to input.jpg
}
}
buf.reserve(1024*200); // horror! probably always lose all data in buf after offset initSize
PS:我没有发现任何权威来源(标准,TC PL等)明确同意或不同意我提出的上述建议.但是在这里可用的所有实现(VC,g,ICC)下,上面的例子工作正常.
这是另一个例子,引自’TC PL,4e’第1041页,注意函数的第一行使用reserve()而不是resize():
void fill(istream& in,string& s,int max)
// use s as target for low-level input (simplified)
{
s.reserve(max); // make sure there is enough allocated space
in.read(&s[0],max);
const int n = in.gcount(); // number of characters read
s.resize(n);
s.shrink_to_fit(); // discard excess capacity
}