【问题标题】:How to avoid std::string copy on protobuf reflection SetString()?如何避免 protobuf 反射 SetString() 上的 std::string 复制?
【发布时间】:2021-04-11 09:17:10
【问题描述】:

有什么方法可以避免std::string复制void SetString(Message * message, const FieldDescriptor * field, std::string value) const

可以用const char* datasize_t data_size设置吗?

【问题讨论】:

  • 在 C++17 中,std::string_view 已为此目的引入。但是,您必须小心使用它:std::string_view 依赖于所查看内容的生命周期,而您(程序员)负责考虑这一点。 (我必须承认,我真的不确定这是否适用于 Google 的 protobuf。)

标签: c++ string performance protocol-buffers


【解决方案1】:

有什么方法可以避免 std::string 复制 void SetString(Message * message, const FieldDescriptor * field, std::string value) const

是的。 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 对象。

【讨论】:

  • API SetString 接受 std:string 而不是 std::string&&std::move 在这种情况下如何工作?
  • 使用std::movevalue 参数被移动构造。所以没有副本。
【解决方案2】:

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

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

【讨论】:

  • 在我的例子中,它与反射 API SetString 有关,所以不是直接设置字段。
猜你喜欢
  • 1970-01-01
  • 2011-06-24
  • 2017-10-30
  • 2016-05-21
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多