简体   繁体   中英

Using a protobuf map of protobuf objects in C++

I cannot seem to find any explicit mention of how protobuf maps that use non-scalar values can be manipulated in C++. For example consider this proto file:

syntax = "proto3"
message X{
  uint32 name = 1;
}

message Y{
  map<string, X> values = 1;
}

Notice that X is non-scalar. How would I go about inserting something into this map in C++? Do I need to dynamically allocate a X object or that is not necessary? For example are both pieces of code below correct? For the dynamically allocated one, would I need to explicitly deallocate the pointer after the insertion in the map? If yes what is the proper way to deallocate the pointer after copying the data in the map?

code 1:

Y y;
X * x = new X();
x->set_name(123);
auto map = y.mutable_values();
(*map)["key value"] = *x;

code 2:

Y y;
X x;
x.set_name(123);
auto map = y.mutable_values();
(*map)["key value"] = x;

Proto map field behave generally like standard library maps

Both your examples make a copy of the proto; so they don't touch the original object. The one where the message is allocated on the stack would need to be deleted separately via delete or (better) a std::unique_ptr .

But the most normal way to "insert" a value is just by using operator[] . Like in standard library maps, this will create a default instance of the value if it's not already present:

Y y;
X& x = (*y->mutable_values())["key"];
x.set_name(123);

If you already have an instance of X that you want to insert, the easiest way is to use std::move :

Y WrapValue(X value) {
  Y y;
  (*y.mutable_values())["key"] = std::move(value);
  return y;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM