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操作。