C++ assignment operator overload

Some notes on overloading the assignment operator

Using the code from GAPBS as an example

CSRGraph& operator=(CSRGraph& other) {
    if (this != &other) {
        if (!is_transpose_)
            ReleaseResources();
        directed_ = other.directed_;
        num_edges_ = other.num_edges_;
        num_nodes_ = other.num_nodes_;
        out_index_ = other.out_index_;
        out_neighbors_ = other.out_neighbors_;
        in_index_ = other.in_index_;
        in_neighbors_ = other.in_neighbors_;
    }
    return *this;
}

 

The arguments has to be supplied with a reference “&”, otherwise there would be an infinite loop. The return also needs to be referenced.

In the end this returns the current object, with *this.

If this operator is overloaded, the assign operator is implicitly deleted

https://en.cppreference.com/w/cpp/language/copy_assignment

We can also potentially supply a double referenced argument

  CSRGraph& operator=(CSRGraph&& other) {
  if (this != &other) {
      if (!is_transpose_)
          ReleaseResources();
    directed_ = other.directed_;
    num_edges_ = other.num_edges_;
    num_nodes_ = other.num_nodes_;
    out_index_ = other.out_index_;
    out_neighbors_ = other.out_neighbors_;
    in_index_ = other.in_index_;
    in_neighbors_ = other.in_neighbors_;
    other.num_edges_ = -1;
    other.num_nodes_ = -1;
    other.out_index_ = nullptr;
    other.out_neighbors_ = nullptr;
    other.in_index_ = nullptr;
    other.in_neighbors_ = nullptr;
    other.flags_ = nullptr;
    other.offsets_ = nullptr;

  }
  return *this;
}

The double reference “&&” allows the object to be modified. As we can see, the values of “other” can be updated inside the assignment operator.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s