Matt Stokes
Matt Stokes

Reputation: 4958

C++ proto2 nested message has field checks

In C++ proto2 is it required to do a has_ check before trying to access nested proto message fields?

message Foo {
  optional Bar1 bar_one = 1;
}

message Bar1 {
  optional Bar2 bar_two = 2;
}

message Bar2 {
  optional int value = 3;
}
Foo foo;
if (!foo.has_bar_one() || !foo.bar_one().has_bar_two() || !foo.bar_one().bar_two().has_value()) {
  // No value
}

or is it fine to just do:

if (!foo.bar_one().bar_two().has_value()) {
  // No value
}

Upvotes: 1

Views: 620

Answers (1)

Clément Jean
Clément Jean

Reputation: 1916

After checking the generated code, it seems your second approach will do just fine. The generated code for bar_one is:

inline const ::Bar1& Foo::_internal_bar_one() const {
  const ::Bar1* p = bar_one_;
  return p != nullptr ? *p : reinterpret_cast<const ::Bar1&>(
      ::_Bar1_default_instance_);
}
inline const ::Bar1& Foo::bar_one() const {
  // @@protoc_insertion_point(field_get:Foo.bar_one)
  return _internal_bar_one();
}

and basically what this is doing is that, it will provide the object if it is set, and it will provide a default instance if its not. This will do the same for bar_two and for value.

So in the end if you check has_value, and its true, it means all the above objects are set, and if its false, at least value is not set. So if you just care about value, your second check will do just fine.

Upvotes: 3

Related Questions