Protobuf:set_allocated_ *是否会删除分配的对象? [英] Protobuf: Will set_allocated_* delete the allocated object?

查看:561
本文介绍了Protobuf:set_allocated_ *是否会删除分配的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个小的protobuf代码(简化了,只包含必要的内容):

I have this small protobuf code (simplified, only the necessary is contained):

message ParamsMessage {
    required int32 temperature = 1;
}

message MasterMessage {
    enum Type { GETPARAMS = 1; SENDPARAMS = 2;}
    required Type type = 1;

    optional ParamsMessage paramsMessage = 2;

}

我现在通过以下方式创建MasterMessage:

I now create a MasterMessage in the following way:

ParamsMessage * params = new ParamsMessage();
params->set_temperature(22);
MasterMessage master;
master.set_type(MasterMessage::SENDPARAMS);
master.set_allocated_paramsmessage(params);

问题是:我是否必须(在处理完消息后)删除 params 消息,还是protobuf会为我删除它?我在文档中找不到任何内容。

The question is: Do I have to (after dealing with the message) delete the params Message, or will protobuf delete it for me? I cannot find anything in the docs.

推荐答案

由于提出了问题,我一直在寻找答案。也许有人也对该答案感兴趣。

Since asking the question I have continued to find the answer. Maybe someone is interested in the answer, too.

从此处:https://developers.google.com/protocol-buffers/docs/reference/cpp-generation


void set_allocated_foo(string * value):将字符串对象设置为
字段,并释放前一个字段值(如果存在)。如果字符串
指针不为NULL,则消息将获得分配的
字符串对象的所有权,并且has_foo()将返回true。否则,如果值
为NULL,则其行为与调用clear_foo()相同。 string *

void set_allocated_foo(string* value): Sets the string object to the field and frees the previous field value if it exists. If the string pointer is not NULL, the message takes ownership of the allocated string object and has_foo() will return true. Otherwise, if the value is NULL, the behavior is the same as calling clear_foo(). string*

release_foo():释放字段的所有权并返回字符串对象的
指针。调用此方法后,调用者将获得分配的字符串对象的
所有权,has_foo()将返回false,
和foo()将返回默认值。

release_foo(): Releases the ownership of the field and returns the pointer of the string object. After calling this, caller takes the ownership of the allocated string object, has_foo() will return false, and foo() will return the default value.

这意味着:只要您打电话给 release _ * ,protobuf就会处理删除对象。如果在处理Protobuf消息后需要该对象,则需要使用 release _ * 释放它,这将阻止Protobuf删除您的对象。

Which means: As long as you do not call release_*, protobuf will take care of deleting the object. If you need the Object after dealing with the Protobuf Message, you need to relase it using release_*, which will prevent Protobuf to delete your object.

这篇关于Protobuf:set_allocated_ *是否会删除分配的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆