【问题标题】:Protobuf: Will set_allocated_* delete the allocated object?Protobuf:set_allocated_* 会删除分配的对象吗?
【发布时间】:2015-11-27 15:57:42
【问题描述】:

我有这个小 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 会为我删除它?我在文档中找不到任何内容。

【问题讨论】:

    标签: c++ protocol-buffers


    【解决方案1】:

    自从提出这个问题以来,我一直在寻找答案。也许有人也对答案感兴趣。

    从这里:https://developers.google.com/protocol-buffers/docs/reference/cpp-generated

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

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

    这意味着:只要您调用release_*,protobuf 就会负责删除该对象。如果您在处理完 Protobuf 消息后需要 Object,则需要使用 release_* 释放它,这将防止 Protobuf 删除您的对象。

    【讨论】:

    • 如果我调用 myMessage.set_allocated_submessage(&submessage),最后总是会出现分段错误(对象破坏?)。只有当我手动 myMessage.release_submessage() 时它才能解决。如果我不使用我的 subMessage,我不明白为什么我会有分段...你认为我的问题需要一个独立的帖子吗?
    • 是的,你应该把它作为一个独立的问题发布。
    • @Maxime.D - 长期死问题,但这可能是因为双重免费。正如帖子所说,protobuf 将为您删除它。不要将子消息留在堆栈上。
    • @Alex 谢谢,但我在发布问题后得到了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2012-12-24
    • 2010-09-21
    相关资源
    最近更新 更多