如何将 protobuf 的 boost::shared_ptr 指针传递给函数?
How do I pass protobuf's boost::shared_ptr pointer to function?
我必须通过一个 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 上的库函数超出范围导致分段错误。
方法一:
oPerson.set_allocated_profile(pProfile.get());
方法二:
oPerson.set_allocated_profile(&*pProfile);
方法 1 和方法 2 是等效的,因为 Protobuf 消息不会超载 operator&
。
Protobuf 在内部管理生命周期(我认为是 Copy-On-Write 语义),所以我更喜欢值语义。
我永远不确定所有权是否(以及如何)通过分配的 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;
我必须通过一个 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 上的库函数超出范围导致分段错误。
方法一:
oPerson.set_allocated_profile(pProfile.get());
方法二:
oPerson.set_allocated_profile(&*pProfile);
方法 1 和方法 2 是等效的,因为 Protobuf 消息不会超载 operator&
。
Protobuf 在内部管理生命周期(我认为是 Copy-On-Write 语义),所以我更喜欢值语义。
我永远不确定所有权是否(以及如何)通过分配的 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;