2017-04-20 128 views
1

我必须通过boost::shared_ptr如何将protobuf的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时,指针超出范围而导致分段错误。

方法1:

oPerson.set_allocated_profile(pProfile.get()); 

方法2:

oPerson.set_allocated_profile(&*pProfile); 
+2

努力帮助没有更多的背景:回顾你的一生的范围并确保内存在使用时仍然有效。 –

回答

2

方法1和2是等效自的Protobuf消息不超载operator&

Protobuf在内部管理生命周期(我认为写时复制语义),所以我倾向于整个价值语义。

我从来不确定是否(以及如何)使用分配的设置者(set_allocated_*)传输所有权。如果你找到一个文件来源,请告诉我!

Iffset_allocated_profile取得指针的所有权,那么您的方法都不正确。您需要从拥有的共享指针释放指针(请参阅How to release pointer from boost::shared_ptr?)。

IFFset_allocated_profile取得所有权,我宁愿写:

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

或等价:

*oPerson.mutable_profile() = *pProfile;