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.