How do I pass protobuf's boost::shared_ptr pointer to function?

邮差的信 提交于 2020-01-24 17:07:10

问题


I have to pass a boost::shared_ptr:

boost::shared_ptr<Protobuf::Person::Profile> pProfile =
      boost::make_shared<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.

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.

Method 1:

oPerson.set_allocated_profile(pProfile.get());

Method 2:

oPerson.set_allocated_profile(&*pProfile);

回答1:


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

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

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 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 does not take ownership, I'd prefer to write:

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

Or equivalently:

*oPerson.mutable_profile() = *pProfile;


来源:https://stackoverflow.com/questions/43514048/how-do-i-pass-protobufs-boostshared-ptr-pointer-to-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!