我正在使用 C++ 开发一个函数,其目的是将 num_bytes
从一个 vector 移动到另一个 vector 。
这是我函数的相关部分
// Grab a pointer to the vector currently in use
std::vector<unsigned char> *bytes = ¤tBuffer();
// Calculate un-parsed data in current vector
size_t num_bytes = static_cast<size_t>(currentBuffer().size() - pos_);
// Added in to test that it is working
std::cout << "Byte before: " << (*bytes)[pos_] << std::endl;
// Move num_bytes from pos_ in currentVector to [0] in otherBuffer
if (num_bytes) {
memmove(&(otherBuffer()[0]), &((*bytes)[pos_]), num_bytes);
}
// I now want to use otherBuffer as currentBuffer
bytes = &otherBuffer();
// Reset size of new buffer
bytes->resize(num_bytes);
// Reset position of new buffer
pos_ = 0;
// Added in to test that it is working
std::cout << "Byte after: " << (*bytes)[pos_] << std::endl;
当我使用真实数据运行它时,我从两个 cout 语句中得到两个不同的结果,理想情况下是 currentVector[pos_]
和 otherVector[0]
的字节值> 在 memmove 之后应该是一样的。
知道哪里出了问题吗?我认为错误在 memmove
中,但我不知道它可能是什么。
谢谢!
最佳答案
您需要在将数据复制到缓冲区之前调整其大小,否则您可能会写入超出其他 vector 的内部分配缓冲区的内容。
但是,使用经典的 C++ 方法会更好:
otherBuffer().assign(currentBuffer().begin() + pos, currentBuffer().end());
所有你需要的 - 没有调整大小,没有 memmove(memcpy 在这种情况下可能会更有效......)。
关于c++ - 在缓冲区之间移动字节时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38594718/