c++ - 在protobuf中,copyFrom优先于赋值吗?

标签 c++ protocol-buffers

以下代码将在运行时失败:

auto cell = addFilterCell(m_filterSlot, idx, odx, section_idx, 48000);
if(request->has_iir()) {
    auto filter = cell->mutable_iir();
    filter->CopyFrom(request->iir());
} else if(request->has_fir()) {
    auto filter = cell->mutable_fir();
    filter->CopyFrom(request->iir()); // Runtime failure

因为我尝试将 IIR 消息复制到 FIR 消息中。 但如果我使用赋值,错误的代码将在编译时失败:

if(request->has_iir()) {
    auto filter = cell->mutable_iir();
    *filter = request->iir();
} else if(request->has_fir()) {
    auto filter = cell->mutable_fir();
    *filter = request->iir();  //compile time error

但是,我看到很多 copyFrom 使用情况,值得鼓励 here 。 从我的角度来看,在上述情况下,使用赋值更安全。 使用赋值可能有哪些缺点?

根据这段生成的代码,在内部,赋值运算符是 copyFrom 的包装器。

class FilterCell : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dio.endpoint.FilterCell) */ {
 public:
  FilterCell();
  virtual ~FilterCell();

  FilterCell(const FilterCell& from);

  inline FilterCell& operator=(const FilterCell& from) {
    CopyFrom(from);
    return *this;
  }

最佳答案

您问题的答案在 the link you provided .

"The assignment operator simply wraps CopyFrom, so the behavior is exactly the same. Stylistically we prefer to use CopyFrom over =, because it can be an expensive operation and = makes it look deceptively simple. The operator= overload primarily exists for compatibility with STL, but of course you're free to use it as you choose."

强调我的

它表示赋值运算符已重载,并且简单地包装了 copyFrom() 函数。因此两者之间没有行为差异。

关于c++ - 在protobuf中,copyFrom优先于赋值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74715054/

相关文章:

c++ - 在带有整数的控制台中显示无关紧要的数字

c++ - 如何从C++代码中绘制类图

c++ - 从服务器下载图像(cUrl,但采纳建议)C++

go - 如何使用 ProtoBuf 下载文件

f# - Protocol Buffer 是否可用于 F#?

c# - 判断C#中设置了哪个 'oneof' proto3字段

c++ - 从嵌入式 C/C++ 逻辑中删除 goto 语句

c++ - 使用 IMediaSeeking 检测视频结尾

python - 将 .profo 文件的文件夹编译为多种语言

python - 从 C 和 Python 解析用户定义的协议(protocol)