Home > Mobile >  In protobuf, is copyFrom preferred to assignment?
In protobuf, is copyFrom preferred to assignment?

Time:12-08

The following code will fail at runtime :

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

Because I try to copy a IIR message into a FIR messages. But if I used assignment, the wrong code would fail at compile time :

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

However, I see a lot of copyFrom usage, and it is encouraged here. From my point of view, in the above case, using assignment is safer. What are the possible downsides of using assignment ?

Internally, the assignment operator is a wrapper around copyFrom, according to this piece of generated code.

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;
  }

CodePudding user response:

The differences between them is that the copyFrom does deep copy, whereas the assignment = does shallow copy. copyFrom is usually recommended because most of the time we need to ensure that all the values are copied, and for large objects/variables shallow copy is not feasible/recommended anyway.

Apart from that, built-in functions manipulating message objects have error checking and validation (most of the time by design), which can help prevent issues such as data corruption or security vulnerabilities.

CodePudding user response:

The answer to your question is in 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."

emphasis mine

It says that the assignment operator is overloaded and simply wraps the copyFrom() function. So there is no behavioural difference between the two.

  • Related