0

这是我的工作代码:

size_t FileReader::Read(ByteVector& output)
{
    output.resize(m_elementSize * m_blockSize);
    size_t read = fread(&output[0], m_elementSize, m_blockSize, m_file);
    output.resize(read);
    return read;
}

但是以前我尝试过的代码output.reserve(m_elementSize * m_blockSize);

据我所知reserve,只是在内存中为容器找到了位置。resize做同样的事情,还将内存从垃圾更改为某些给定值并更改容器大小。

fread第一个参数是void *,它与unsigned char *我的问题相同,为什么我在调用fread.

为什么会这样?因为需要 void 指针并且它不使用类fread写入内存。vector

PS忘了说typedef std::vector<unsigned char> ByteVector

4

2 回答 2

4

如果向量最初为空,则output[0]调用未定义的行为(无论您保留了多少空间),并且在某些平台上它可能会引发异常。

于 2013-08-21T12:32:22.493 回答
1

Have found the problem, now I use code I called working

I wanted to avoid unnecessary resize because it works with data in memory, however after reserve output[0] do not exists.

What is more after read vector size would be zero and resize would destroy read data.

于 2013-08-21T12:39:00.647 回答