简体   繁体   中英

How to set a preallocated message as field using reflection in protobuf on C++?

I have a code like this:

TestMessage* output;
::google::protobuf::Message* input;
// ...
auto extension_field = input->GetDescriptor()->extension(i);
// ...
auto reflection = output->GetReflection();
reflection->MutableMessage(output, extension_field)->CopyFrom(*input);

This code takes two messages, checks that the one is an extension of the other, copies input message to the corresponding extension field of output message.

I want to optimise it - and replace copying with "moving". How can I do it using reflection ?

The closest you can get is to use Reflection::Swap in place of CopyFrom . The top-level object won't be consumed, but all of its child objects (strings, submessages, etc.) will be.

auto msg = reflection->MutableMessage(output, output_field);
msg->GetReflection()->Swap(msg, input);
delete input;

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