复制平面缓冲区以供以后处理

时间:2019-05-15 02:25:39

标签: c++ c++11 serialization flatbuffers

我有一个服务接收一列flatbuffers消息流,对于大多数处理来说都是内联的,但是形成一些消息后,我需要保存它们以便以后处理:

char buf[] = recv(...);
const MyMessage* msg = GetSizePrefixedMyMessage(buf);
process(msg);
MyMessage *saved = Copy(msg) ??? how can I copy it?

因为flatbuffers消息的每个字段都是成员函数而不是真实数据,所以我不能只是memcpy,对吗?有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您不能memcpy访问指针msg,但是可以简单地memcpy原始buf

答案 1 :(得分:0)

  

MyMessage *保存=复制(msg)???我该如何复制?

鉴于已定义,您应该能够使用复制构造函数将其复制:

MyMessage saved(*msg); // If you like to have it on the stack, 
    // but will get destroyed as soon as you leave the scope. 
    // Preferred way unless MyMessage is big
MyMessage* saved= new MyMessage(*msg); // Could be auto instead of MyMessage*. 
    // We don't do this anymore on modern C++, you need a call to delete
auto saved= std::make_unique<MyMessage>(*msg); // This gets deleted automatically
    // falling out of scope

如果您没有副本构造函数,而是赋值运算符:

MyMessage saved; 
saved= *msg; // Copy
MyMessage* saved= new MyMessage();
*saved= *msg; // Copy
auto saved= std::make_unique<MyMessage>();
*saved= *msg; // Copy

鉴于这两个失败,如果MyMessage是一个简单的结构(没有指针,没有虚函数),则可以这样做:

MyMessage saved;
memcpy(&saved, msg, sizeof(MyMessage));
MyMessage* saved= new MyMessage();
memcpy(saved, msg, sizeof(MyMessage));
auto saved= std::make_unique<MyMessage>();
memcpy(saved.get(), msg, sizeof(MyMessage));