如何将protobuf的boost :: shared_ptr指针传递给函数? [英] How do I pass protobuf's boost::shared_ptr pointer to function?

查看:364
本文介绍了如何将protobuf的boost :: shared_ptr指针传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须通过boost::shared_ptr:

boost::shared_ptr<Protobuf::Person::Profile> pProfile =
      boost::make_shared<Protobuf::Person::Profile>();

是protobuf的指针,指向protobuf的函数oPerson.set_allocated_profile(pProfile),但是oPerson.set_allocated()需要一个指向Protobuf::Person::Profile的指针.

which is protobuf's pointer, to a protobuf's function oPerson.set_allocated_profile(pProfile) but oPerson.set_allocated() expects a pointer to Protobuf::Person::Profile.

我尝试了几种方法,但是我认为当我尝试使用pbjson::pb2Json将protobuf对象转换为JSON时,这是一个基于快速json的库函数,指针超出范围会导致分段错误.

I have tried couple of ways but I think when I try to convert protobuf object to JSON using pbjson::pb2Json which is a library function built on rapid json, the pointer goes out of scope causing segmentation fault.

方法1:

oPerson.set_allocated_profile(pProfile.get());

方法2:

oPerson.set_allocated_profile(&*pProfile);

推荐答案

方法1和方法2是等效的,因为Protobuf消息不会超载operator&.

Method 1 and 2 are equivalent since Protobuf messages don't overload operator&.

Protobuf在内部管理生命周期(并且我认为写时复制语义),因此,我始终倾向于使用值语义.

Protobuf manages lifetimes (and I think Copy-On-Write semantics) internally, so I'd favour value semantics throughout.

我永远无法确切确定所有权是否(以及如何)与分配的设置员(set_allocated_*)一起转让.如果您找到记录该文件的来源,请告诉我!

I'm never exactly sure whether (and how) ownership is transferred with the allocated setters (set_allocated_*). If you find a source that documents it, please tell me!

Iff set_allocated_profile拥有指针的所有权,那么您的两种方法都不正确.您需要从自己的共享指针中释放指针(请参阅如何从boost :: shared_ptr释放指针?).

Iff set_allocated_profile takes ownership of the pointer, then neither of your approaches is correct. You'd need to release the pointer from your owning shared pointer (see How to release pointer from boost::shared_ptr?).

Iff set_allocated_profile 拥有所有权,我更愿意这样写:

Iff set_allocated_profile does not take ownership, I'd prefer to write:

oPerson.mutable_profile()->CopyFrom(*pProfile);

或等效地:

*oPerson.mutable_profile() = *pProfile;

这篇关于如何将protobuf的boost :: shared_ptr指针传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆