我将结构复制到向量中,然后将其放回结构中。为什么会发生此错误?错误使用std::copy
?
复制时,我使用了std::copy
,并一一复制了结构。
这是代码:
struct test_msg
{
int32_t msg_type =0;
int32_t msg_id =0;
int32_t src = 0 ;
int32_t dst = 0;
std::string data;
bool Serialize(std::vector<char> &out) {
out.clear();
std::copy(&msg_type, &msg_type + sizeof(msg_type), std::back_inserter(out));
std::copy(&msg_id,&msg_id + sizeof(msg_id), std::back_inserter(out));
std::copy(&src,&src + sizeof(src), std::back_inserter(out));
std::copy(&dst,&dst + sizeof(dst), std::back_inserter(out));
std::copy(json_string.begin(),json_string.end(), std::back_inserter(out));
return true;
};
bool Deserialize(std::vector<char> &out) {
int last_index = 0;
std::copy(out.begin() + last_index, out.begin() +last_index + sizeof(msg_type), &msg_type); last_index += sizeof(msg_type);
std::copy(out.begin() + last_index, out.begin() +last_index + sizeof(msg_id), &msg_id); last_index += sizeof(msg_id);
std::copy(out.begin() + last_index, out.begin() +last_index + sizeof(src), &src); last_index += sizeof(src);
std::copy(out.begin() + last_index, out.begin() +last_index + sizeof(dst), &dst); last_index += sizeof(dst);
// std::copy(out.begin() + last_index, out.begin() +last_index + sizeof(synchronous), &synchronous); last_index += sizeof(synchronous);
std::copy(out.begin() + last_index, out.end(), std::back_inserter(json_string));
return true;
};
};
int main(int argc, char *argv[]) {
testmsg msg;
msg.msg_type =11;
msg.msg_id =22;
msg.src =33;
msg.dst =44;
msg.json_string = "this is test!this is test!this is test!\0";
std::vector<char> data;
msg.Serialize(data);
IpcJsonMessage msg2;
msg2.Deserialize(data);
return 1;
}
答案 0 :(得分:3)
问题是您正在使用std::copy
复制int32s
,这将迭代int32,但是您认为它会迭代字节:
std::copy(&msg_type, &msg_type + sizeof(msg_type), std::back_inserter(out));
在这种情况下,您很可能会从偏移量0、4、8、12(首先是LSB)复制4个非连续字节,因为迭代的工作方式与增加C指针时的方式相同(即int32* pX; pX++;
将pX递增1 int32-> 4字节)。每次迭代都会从内存中加载一个int32,但只会将最低有效字节添加到char向量中。
考虑一下std :: copy如何展开:
int32* pIter;
int32* pEnd; //pIter+4 i.e 16 bytes ahead of pIter
vector<char> dest;
while (pIter < pEnd)
{
int32 value = *pIter;
dest.push_back (value); //loses the upper 24 bits of value
pIter++;
}
有关完整说明,请参见此处:Copy Memory to std::copy
以下是在Visual Studio中运行代码段的屏幕转储:
关于解决问题的方法,请看一下:Is it possible to serialize and deserialize a class in C++?