Question

I'm new to the google protobuf and what to know is there any different between following methods:

1) 
foo.mutable_bar()->set_somefield(...)

and

2)
nestedmsg = foo.bar(); 
nestedmsg.set_somefield() (where bar is message) 

?

As I found foo.bar() is not working for me. The different in the docs is that mutable call returns pointer instead default_instance. But why the second way is not working?

Was it helpful?

Solution

Your second version shouldn't even compile: bar() returns a const reference, but set_somefield() is not a const method. Do not use const_cast to get around this!

The difference between the methods is that mutable_bar() actually initializes the bar field with a new sub-message if it is not already present. That is, if has_bar() will always return true after mutable_bar() even if it was false before hand. bar(), on the other hand, never modifies the message, so does not affect has_bar(). If the bar field isn't set, then bar() returns a reference to the type's default instance, which you should never modify -- that's why it's const.

If you need to modify the sub-message, you must always use the mutable_ variant. Don't worry, it never returns a null pointer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top