我必须传递一个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 的指针: :简介
。
我尝试了几种方法,但我认为当我尝试使用 pbjson::pb2Json
(一个基于快速 json 构建的库函数)将 protobuf 对象转换为 JSON 时,指针超出范围,导致段错误。
方法一:
oPerson.set_allocated_profile(pProfile.get());
方法2:
oPerson.set_allocated_profile(&*pProfile);
最佳答案
方法 1 和 2 是等效的,因为 Protobuf 消息不会重载 operator&
。
Protobuf 在内部管理生命周期(我认为是 Copy-On-Write 语义),因此我自始至终都支持值语义。
我永远不确定所有权是否(以及如何)通过分配的 setter (set_allocated_*
) 进行转移。如果您找到记录它的来源,请告诉我!
如果 set_allocated_profile
取得了指针的所有权,那么您的方法都不正确。您需要从您拥有的共享指针中释放该指针(请参阅 How to release pointer from boost::shared_ptr? )。
如果 set_allocated_profile
确实不取得所有权,我更愿意写:
oPerson.mutable_profile()->CopyFrom(*pProfile);
或者等效的:
*oPerson.mutable_profile() = *pProfile;
关于c++ - 如何将 protobuf 的 boost::shared_ptr 指针传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514048/