简体   繁体   中英

How to assign nested protobuf without copying in C++?

I have a protobuf, one fields of which is another protobuf, and I have an instance of that latter type ready. How can I inject this new instance into another protobuf without copying?

I think you are looking for set_allocated_* from here

void set_allocated_foo(Bar* bar): Sets the Bar object to the field and frees the previous field value if it exists. If the Bar pointer is not NULL, the message takes ownership of the allocated Bar object and has_foo() will return true. Otherwise, if the Bar is NULL, the behavior is the same as calling clear_foo().

If you're using proto3, the compiled class defines move constructor. So you can simply move it.

Proto definition:

syntax="proto3";

message A {
    string s = 1;
}

message B {
    A a = 1;
}

Move A into B:

A a;
a.set_s("hello");
B b;
(*b.mutable_a()) = std::move(a);

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