C++proto2嵌套消息具有字段检查



在C++proto2中,在尝试访问嵌套的proto消息字段之前,是否需要进行has_检查?

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
}

还是直接做:

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

检查生成的代码后,您的第二种方法似乎会很好。生成的bar_one代码为:

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();
}

基本上,它所做的是,如果设置了对象,它将提供对象,如果没有设置,它将为对象提供默认实例。这将对bar_twovalue执行相同的操作。

因此,如果最后检查has_value,并且它为true,则意味着以上所有对象都已设置,如果它为false,则至少未设置value。所以,如果你只关心value,你的第二次检查会很好。

最新更新