C++ 将泛型protobuf复制到堆上的新对象中

C++ 将泛型protobuf复制到堆上的新对象中,c++,c++11,protocol-buffers,deep-copy,C++,C++11,Protocol Buffers,Deep Copy,我想复制一个genericconstprotobuf,以便进一步操作。我想出了 Message* myfn(const Message *msg) { Message *copy = msg->New(); copy->CopyFrom(*msg); // do stuff return copy; } 这是正确的/惯用的吗?还是有更好的方法(可能是C++11特有的)?这是正确的 如果您想要类型安全,一点模板魔术可以帮助您: template<class Ms

我想复制一个generic
const
protobuf,以便进一步操作。我想出了

Message* myfn(const Message *msg) {
  Message *copy = msg->New();
  copy->CopyFrom(*msg);
  // do stuff
  return copy;
}
这是正确的/惯用的吗?还是有更好的方法(可能是C++11特有的)?

这是正确的

如果您想要类型安全,一点模板魔术可以帮助您:

template<class Msg, 
         std::enable_if_t<std::is_base_of<protobuf::Message,
                                          Msg>::value>>
std::unique_ptr<Msg> clone(const Msg* msg)
{
  std::unique_ptr<Msg> p(msg->New());
  p->CopyFrom(*msg);
  return p;
}
模板
std::唯一的ptr克隆(const Msg*Msg)
{
std::unique_ptr p(msg->New());
p->CopyFrom(*msg);
返回p;
}
您将看到,我已将protocol buffers对象包装在一个唯一的\u ptr中。这提供了一些异常安全性,并具有可转换为共享ptr的附加优势

为什么这是个好主意?那么,考虑一个称为FO的协议缓冲对象,它有2个字符串成员,称为BAR和BAZ:

void test(const Foo* source_foo)
{
  // clone and convert the unique_ptr to shared_ptr
  std::shared_ptr<Foo> myclone(clone(source_foo));

  myclone->bar() += " cloned";
  myclone->baz() += " cloned again";

  // get a shared_ptr to the members:
  auto mybar = std::shared_ptr<const std::string>(myclone, &myclone->bar());
  auto mybaz = std::shared_ptr<const std::string>(myclone, &myclone->baz());

  give_away(mybar);
  do_something_else(mybaz);

  // at this point the use_count of myclone is at least 3. 
  // if give_away results in holding on to the shared_ptr 
  // to string then myclone will be kept 
  // alive until the last shared_ptr goes away 

}
void测试(const Foo*source\u Foo)
{
//克隆唯一的\u ptr并将其转换为共享的\u ptr
std::shared_ptr myclone(clone(source_foo));
myclone->bar()+=“已克隆”;
myclone->baz()+=“再次克隆”;
//向成员获取共享的ptr:
自动mybar=std::shared_ptr(myclone,&myclone->bar());
auto mybaz=std::shared_ptr(myclone,&myclone->baz());
赠送(我的酒吧);
做点别的(mybaz);
//此时myclone的使用计数至少为3。
//如果放弃会导致保留共享的ptr
//若要设置字符串,则将保留myclone
//直到最后一次共享的\u ptr消失
}

这可能已经过时了吗?我不能用那样的函数
std::shared_ptr myclone(clone(testMsg)):
为我提供了
错误:调用“clone(ProtoTestMsg*&)”std::shared_ptr myclone(clone(testMsg)),没有匹配的函数
@madmax文档中仍然列出了CopyFrom方法:但有可能事情已经发生了变化。我的问题不是CopyFrom方法,而是克隆方法。(我称之为cloneMsg)->
错误:调用'cloneMsg(ProtoTestMsg*&)'std::unique_ptr myclone(static_cast(cloneMsg(testMsg)),没有匹配的函数
@madmax在没有看到您的代码的情况下很难进行评论。我知道这并不容易,因为它涉及到编译proto的步骤files@RichardHodges我得到了与@madmax相同的编译器错误。我至少花了一个小时来研究这个问题,但我不知道如何正确调用
clone()
。这是否是C++语言版本的问题?code>.proto文件已成功生成。