Do I need to delete objects passed to google protocol buffer (protobuf)?

谁说我不能喝 提交于 2021-01-01 06:51:16

问题


I have simple messages:

message SmallValue {
    int32 val = 1;
}
message Value {
    int32 val1 = 1;
    int32 val2 = 2;
    SmallValue val3 = 3;
}
message SendMessage {
    int32 id = 1;
    oneof message {
        Value value= 2;
}

My piece of code:

// create new pointer for smallValue
SmallValue* smallValue = new SmallValue();
smallValue->set_val3(3);

// create new object value and set_allocated_val3
Value value;
value.set_val1(1);
value.set_val2(2);
value.set_allocated_val3(smallValue);

// create new object message and set_allocated_value
SendMessage message;
message.set_id(0);
message.set_allocated_value(&value);

// after some work, release value from message
message.release_value();

And my questions are:
1. After calling message.release_value() is it OK not to call delete &value; as I didn't create new pointer?
2. Will memory of smallValue will be deleted automatically along with value as I didn't call value.release_smallValue();?

// I'm a newbie to C++ as well as protobuf. Please do tell if something odd about my code.

Thanks!


回答1:


It is usually best to avoid using the set_allocated_* and release_* methods; those provide advanced memory-management features that you should not need unless you are really trying to optimize some performance-critical code.

You could rewrite your code like this to avoid having to worry about memory management as much:

SendMessage message;
message.set_id(0);
Value* value = message.mutable_value();
value->set_val1(1);
value->set_val2(2);
value->mutable_val3()->set_val(3);


来源:https://stackoverflow.com/questions/43268845/do-i-need-to-delete-objects-passed-to-google-protocol-buffer-protobuf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!