c++ protobuf 可能会遇到的坑

1.发现存在内存泄露。

程序退出时记得调用:

google::protobuf::ShutdownProtobufLibrary();

这里一定是在程序退出时调用,如果调用后又使用了 protobuf 会出现异常,因为protobuf 中使用构造 会有创建指针,会存入 ShutdownData;

ShutdownProtobufLibrary 源码:

void ShutdownProtobufLibrary() {
  // This function should be called only once, but accepts multiple calls.
  static bool is_shutdown = false;
  if (!is_shutdown) {
    delete internal::ShutdownData::get();
    is_shutdown = true;
  }
}

解决方案:

定义成全局,全局只释放一次

struct A {
    ~A(){
         google::protobuf::ShutdownProtobufLibrary() ;
    }
};
A  _globalProtobuf;

2.内存有异常:

  可能是:protobuf 中的嵌套消息的使用临时变量例:

string sn="1111";

string Algo="3333";

request.set_sn(sn);
request.set_algo(Algo);

如果在其它地方使用可能会有异常;需要去new,退去时记得 release_eventcode

 PointProtos::Event *event = mUploadLogInfoData->add_events();
 string* ans = event->mutable_eventcode();
 (*ans)=key;
 string* tvalue = event->mutable_eventcode();//
 (*tvalue)= value ;

  如果是对象一样:
for(int index = 0;index<info.answer_size();index++)
{
    Detail * detail = rsp.add_detail();
    Answer* ans = detail->mutable_answer();
    Answer temp_ans = info.answer(index);
    ans->copyFrom(temp_ans);
}
 

总结:protobuf 中的嵌套消息的使用主要对set_allocated_和mutable_的使用

1 使用set_allocated_,赋值的对象需要new出来,不能用局部的,这里保存的是对象的指针。

2 使用mutable_,赋值时候,可以使用局部变量,因为在调用的时,内部做了new操作。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

恋恋西风

up up up

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值