How do I pass protobuf's boost::shared_ptr poi

2019-07-22 07:04发布

问题:

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;