[英]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.我有一个 protobuf,其中一个字段是另一个 protobuf,我已经准备好后一种类型的实例。 How can I inject this new instance into another protobuf without copying?如何在不复制的情况下将此新实例注入另一个 protobuf?
I think you are looking for set_allocated_* from here我认为您正在从这里寻找 set_allocated_*
void set_allocated_foo(Bar* bar): Sets the Bar object to the field and frees the previous field value if it exists. void set_allocated_foo(Bar* bar):将 Bar object 设置为字段并释放前一个字段值(如果存在)。 If the Bar pointer is not NULL, the message takes ownership of the allocated Bar object and has_foo() will return true.如果 Bar 指针不是 NULL,则消息获取分配的 Bar object 的所有权,并且 has_foo() 将返回 true。 Otherwise, if the Bar is NULL, the behavior is the same as calling clear_foo().否则,如果 Bar 为 NULL,则行为与调用 clear_foo() 相同。
If you're using proto3, the compiled class defines move constructor.如果您使用的是 proto3,则编译后的 class 定义了移动构造函数。 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 移入 B:
A a;
a.set_s("hello");
B b;
(*b.mutable_a()) = std::move(a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.