c++ - Protobuf : Will set_allocated_* delete the allocated object?

标签 c++ protocol-buffers

我有这个小 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/

相关文章:

c++ - 使用 SSE 内在函数复制少量数据的问题

c++ - 在 C++ 中提高/优化文件写入速度

hadoop - 使用 loadfunc pig UDF 将 protobuf 格式文件加载到 pig 脚本中

node.js - 序列化失败(grpc/node)

java - Java读取protobuf消息时出现异常

c++ - forked进程偶发的栈指针段错误

c++ - C++ 和 Opengl 中的多显示器应用程序

c++ - 处理消息太慢,导致 UI 不稳定、无响应 - 如何使用多线程来缓解这种情况?

c++ - 如何在 linux 上通过 cmake 链接 google protobuf 库?

go - 从 protobuf 中的其他包导入类型定义