【问题标题】:How do I pass protobuf's boost::shared_ptr pointer to function?如何将 protobuf 的 boost::shared_ptr 指针传递给函数?
【发布时间】:2017-04-20 08:23:49
【问题描述】:

我必须通过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(一个基于快速 json 构建的库函数)将 protobuf 对象转换为 JSON 时,指针超出范围导致分段错误。

方法一:

oPerson.set_allocated_profile(pProfile.get());

方法二:

oPerson.set_allocated_profile(&*pProfile);

【问题讨论】:

  • 在没有更多上下文的情况下很难提供帮助:检查您的生命周期并确保内存在使用时仍然有效。

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


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多