As per protobuf docs:
In your generated code, oneof fields have the same getters and setters as regular fields. You also get a special method for checking which value (if any) in the oneof is set.
Setting a oneof field will automatically clear all other members of the oneof. So if you set several oneof fields, only the last field you set will still have a value.
From https://protobuf.dev/reference/cpp/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. The message is free to delete the allocated string object at any time, so references to the object may be invalidated. 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 and foo() will return the empty string/empty bytes
On generating your given Service.proto
file with protoc 3.21.12, I could see the following lines in Service.pb.h
:
// .Foo myfoo = 2;
bool has_myfoo() const;
private:
bool _internal_has_myfoo() const;
public:
void clear_myfoo();
const ::Foo& myfoo() const;
PROTOBUF_NODISCARD ::Foo* release_myfoo();
::Foo* mutable_myfoo();
void set_allocated_myfoo(::Foo* myfoo);
private:
const ::Foo& _internal_myfoo() const;
::Foo* _internal_mutable_myfoo();
public:
void unsafe_arena_set_allocated_myfoo(
::Foo* myfoo);
::Foo* unsafe_arena_release_myfoo();
In your case, you should be able to use like this (as per example in the docs link):
Foo* foo = new Foo;
foo->set_id(1);
...
ServiceMessageRequest service_message_request;
service_message_request.set_allocated_myfoo(foo);
...
Links:
- Protobuf: Will set_allocated_* delete the allocated object?
- Google Protobuf : "mutable_foo()" or "set_allocated_foo()"?