如何避免protobuf反射SetString()上的std::string复制



是否有任何方法可以避免void SetString(Message * message, const FieldDescriptor * field, std::string value) conststd::string复制。

是否可以使用const char* datasize_t data_size进行设置?

是否有任何方法可以避免void SetString(Message*消息,const FieldDescriptor*字段,std::string值(const 的std::字符串复制

是。value参数是通过值传递的,因此您可以调用std::move来移动字符串对象,而不是复制它:

string your_value;
reflect->SetString(message, field, std::move(your_value));

是否可以使用const char*data和size_t data_size进行设置?

不,你不能那样做。由于value参数的类型为std::string,因此必须构造一个具有data指针和data_size长度的std::string对象。到目前为止,为了创建一个带有指针的std::string对象,无法避免复制。

请参阅https://developers.google.com/protocol-buffers/docs/reference/cpp-generated:

void set_foo(字符串&&值((C++11及更高版本(:从传递的字符串开始设置字段的值。调用后,has_foo((将返回true,而foo((则返回值的副本。

最新更新