美文网首页
Protobuf 自定义message中 set_allocat

Protobuf 自定义message中 set_allocat

作者: XBruce | 来源:发表于2020-07-23 17:22 被阅读0次

在使用protobuf的过程中,一般会用到message内使用另一个message作为内部变量的参数类型的情况。如下:

message MyParameter{
    required int32 p1= 1;
    required int32 p2= 2;
}
 
message MainMsg{
    required int32 type = 1;
    MyParameter param= 2;
}

我使用的编程语言是C++,使用过程中注意:

MyParameter* param= new MyParameter();
param->set_p1(22);

MainMsg master;
master.set_type(1);
master.set_allocated_param(param);

有一点需要注意:set_allocated_param()函数的参数的生命周期需要特别注意,因为调用此函数后,master消息只保存了param的指针,如果param是局部变量,那么会导致master消息的参数param访问非法内存。
而且,调用set_allocated_param函数后,master变量会接管param指向的内存,并在结束使用后自行释放。

相关文章

网友评论

      本文标题:Protobuf 自定义message中 set_allocat

      本文链接:https://www.haomeiwen.com/subject/ozlknhtx.html