0

I'm using C++14 with protobuf to code.

In my proto file, I designed a nested message as below:

message Object {
    // something
};

message Response {
    repeated Object list = 1;
};

In my C++ project, I try to insert an element:

Object obj;
Response res;
// res.mutable_list()->Add(obj); // ERROR!
res.mutable_list()->Add()->CopyFrom(obj);

I really don't why but Add(obj) will cause a compile error:

cannot bind 'Object' lvalue to 'Object&&'
res.mutable_info()->Add(obj);

I really couldn't understand why because in the header file, I did find the definitions of the funcitons inline void RepeatedPtrField<Element>::Add(Element&& value) and inline void RepeatedPtrField<Element>::Add(const Element& value). But both res.mutable_list()->Add(std::move(obj)); and res.mutable_list()->Add(obj); will cause some compile errors. Another error is as below, which I totally can't understand what it is:

no matching function for call to 'google::protobuf::RepeatedPtrField::TypeHandler::New(Google::protobuf::Area*&, std::remove_reference<Object&>::type)'
TypeHandler::New(arena_, std::move(value));

res.mutable_list()->Add()->CopyFrom(obj); works but why can't I simply call Add(obj)?

Yves
  • 11,597
  • 17
  • 83
  • 180

1 Answers1

0

Add(Object &&object) function requires object argument to be rvalue reference. You can cast to rvalue reference with std::move.

Object obj;
Response res;
res.mutable_list()->Add(std::move(obj)); // This should work.

However after using std::move, you can not access to obj variable anymore, if you try to acces it you will be greeted with segmentation fault. This is why with protobuf, it is much better to create your child message objects from your parent object.