微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

std :: copy问题,我不知道为什么会发生此错误

如何解决std :: copy问题,我不知道为什么会发生此错误

  1. 我将结构复制到向量中,然后将其放回结构中。为什么会发生此错误错误使用std::copy

  2. 复制时,我使用了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;
}

解决方法

问题是您正在使用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中运行代码段的屏幕转储:

enter image description here


关于解决问题的方法,请看一下:Is it possible to serialize and deserialize a class in C++?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。