如何将protobuf的boost :: shared_ptr指针传递给函数?

时间:2017-04-20 08:23:50

标签: c++ boost shared-ptr rapidjson make-shared

我必须传递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的指针。

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

方法1:

oPerson.set_allocated_profile(pProfile.get());

方法2:

oPerson.set_allocated_profile(&*pProfile);

1 个答案:

答案 0 :(得分:2)

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

Protobuf在内部管理生命周期(我认为写入时复制语义),所以我始终支持值语义。

我永远不确定是否(以及如何)使用分配的setter(set_allocated_*)传输所有权。如果您找到记录它的来源,请告诉我!

Iff set_allocated_profile获取指针的所有权,然后您的方法都不正确。您需要从您自己的共享指针释放指针(请参阅How to release pointer from boost::shared_ptr?)。

Iff set_allocated_profile 取得所有权,我更愿意写:

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

或等效地:

*oPerson.mutable_profile() = *pProfile;