0

Let's consider I have such struct:

struct Cell {
  int x;              
  int y;             
  bool empty = true;
  int dist = 0;
  std::vector<ParrentCoord*> parr_coord = {};

  bool operator==(const Cell c) const;
  bool operator!=(const Cell c) const;
  Cell& operator=(const Cell& c);
  Cell& operator+=(const Cell c);
  Cell& operator+(const Cell c) const;
  bool operator<(const Cell c) const;
};

And two operator's overloading looks like these:

Cell& Cell::operator=(const Cell &c) {
  if (this == &c) return (*this);
  this->empty = false;
  this->x = c.x;
  this->y = c.y;
  this->dist = c.dist;
  std::copy(c.parr_coord.begin(), c.parr_coord.end(), std::back_inserter(this->parr_coord));
  return (*this);
}

Cell& Cell::operator+(const Cell c) const {
  Cell res;
  res.parr_coord.push_back(new ParrentCoord({this->x, this->y}));

  res.x = this->x + c.x;
  res.y = this->y + c.y;
  res.empty = false;
  res.dist = this->dist + 1;
  return (res);
}

The problem is that, when I am assigning a sum of cells a = b + c, where a, b and c belong to cell-class. Everything assigns fine, except parr_coord, it's always empty. I've used debuger to check where exactly it changes. I deciphered, that at the end of operator+, namely return (res) the res.parr_coord size is 1. However, at the beginning of operator=, namely the argument const Cell &c has the changed data, for instance the c.dist was 0 and after summation it turns into the 1. Though, parr_coord size remains 0. Where did I admit a mistake?

JuiceFV
  • 171
  • 11
  • 3
    `operator +` should return a value, not a reference to an about-to-be-destroyed automatic instance. [See this question](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading). – WhozCraig Dec 13 '20 at 19:29
  • @WhozCraig Yes! It really was a bottleneck, thanks. – JuiceFV Dec 13 '20 at 19:41
  • Bottleneck has nothing to do with it. It's *undefined behavior*. The section "Binary arithmetic operators" in the linked question and selected answer are worth reading. – WhozCraig Dec 13 '20 at 19:46

0 Answers0