问题
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