std :: vector调整大小与保留期间的保留时间 [英] std::vector resize vs reserve during fread

查看:145
本文介绍了std :: vector调整大小与保留期间的保留时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的工作代码:

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);

However previous I have tried code which had output.reserve(m_elementSize * m_blockSize);

据我所知reserve只是在容器中的内存中找到了位置. resize进行同样的操作,还将内存从垃圾桶更改为某些给定值,并更改容器大小.

As far as I know reserve just founds place in memory for container. resize do the same, also changes memory from trash to some given values and change container size.

fread第一个参数是void *,它与unsigned char *相同,我的问题是,为什么调用fread时会出现异常.

fread first parameter is void * and it is the same as unsigned char *, my question, why did I get exception while calling fread.

为什么会这样?因为fread使用void指针,并且不使用vector类将其写入内存.

Why is it happening? Because fread takes void pointer and it do not write into memory using vector class.

P.S.忘记提及typedef std::vector<unsigned char> ByteVector

推荐答案

如果向量最初为空,则output[0]会调用未定义的行为(无论您保留了多少空间),在某些平台上,它可能会抛出一个

If the vector is initially empty, then output[0] invokes undefined behaviour (regardless of how much space you have reserved), and on some platforms it may throw an exception.

这篇关于std :: vector调整大小与保留期间的保留时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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