Does Protocol Buffers support move constructor

11,269

Solution 1

As of version 2.6.1, C++ protobuf compiler generates only copy constructors and copy assignment operators. But if your compiler supports return value optimization (and the conditions for it are satisfied) the copy constructor won't be called anyway.

You can add some printing statements into generated code of your messages' copy constructors to see if they are really invoked or not. You can also do it by writing a protoc plugin, so it persists between protoc invocations.

Solution 2

According to https://github.com/google/protobuf/issues/2791 this will be supported in Protobuf version 3.4.0.

Solution 3

  1. If you try to use a assignment operator, RVO will do optimization to prevent an extra copy.

    // RVO will bring the return value to a without using copy constructor.
    SomeMessage a = SomeFooWithMessageReturned();
    
  2. If you want to use std::move to move a lvalue into a list/sub message, etc. Try to use ConcreteMessage::Swap method. The swapped item will be useless.

    // Non-copy usage.
    somemessage.add_somerepeated_message()->Swap(&a);
    somemessage.mutable_somesinglar_message()->Swap(&a);
    // With message copying
    somemessage.add_somerepeated_message()->CopyFrom(a);
    *somemessage.mutable_somesinglar_message() = a;
    
Share:
11,269
Paweł Szczur
Author by

Paweł Szczur

I'm interested in solving real world problems with technology. I am also amazed how important for projects the collaboration and communication is. I'm poking around: C++, Go, AppEngine, Android, CUDA and others.

Updated on July 23, 2022

Comments

  • Paweł Szczur
    Paweł Szczur almost 2 years

    I've checked the move constructor spec and a Message constructor source and didn't find one.

    If there's not, does anyone know about a plan to add it?

    I'm using proto3 syntax, writing a library and considering between return through value vs unique_ptr.