我有这个小 protobuf 代码(简化,只包含必要的):
message ParamsMessage {
required int32 temperature = 1;
}
message MasterMessage {
enum Type { GETPARAMS = 1; SENDPARAMS = 2;}
required Type type = 1;
optional ParamsMessage paramsMessage = 2;
}
我现在通过以下方式创建 MasterMessage:
ParamsMessage * params = new ParamsMessage();
params->set_temperature(22);
MasterMessage master;
master.set_type(MasterMessage::SENDPARAMS);
master.set_allocated_paramsmessage(params);
问题是:我必须(在处理完消息之后)删除 params
消息,还是 protobuf 会帮我删除它?我在文档中找不到任何内容。
最佳答案
自从提出这个问题以来,我一直在寻找答案。也许有人也对答案感兴趣。
从这里:https://developers.google.com/protocol-buffers/docs/reference/cpp-generated
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(): 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 消息后需要 Object,则需要使用 release_*
释放它,这将防止 Protobuf 删除您的对象。
关于c++ - Protobuf : Will set_allocated_* delete the allocated object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33960999/