1

I'm trying to refactoring the following code which relies on classic C-style arrays to make it more C++ like:

fb::Block *blocks[Panel::X][Panel::Y];

void Panel::mechanics(int64_t tick) {
  for (int32_t y = 1; y < Panel::Y; y++) {
    for (int32_t x = 0; x < Panel::X; x++) {
      fb::Block* current = blocks[x][y];
      if (current -- nullptr) {
        continue;
      }
      // Switching the 2 pointers
      blocks[x][y] = blocks[x + 1][y];
      blocks[x + 1][y] = current;
    }
  }
}

The following code is relying on std::array and std::unique_ptr. I need to swap 2 values as I was doing in the previous code but I'm not sure if it's the right way to do it:

std::array<std::array<std::unique_ptr<fb::Block>, Panel::Y>, Panel::X> blocks;

void Panel::mechanics(int64_t tick) {
  for (int32_t y = 1; y < Panel::Y; y++) {
    for (int32_t x = 0; x < Panel::X; x++) {
      std::unique_ptr<fb::Block>& current = blocks[x][y];
      if (!current) {
        continue;
      }
      // Swapping the 2 pointers
      blocks[x][y].swap(blocks[x + 1][y]);
    }
  }
}

Is the swap member the right way to achieve this ?

bquenin
  • 1,470
  • 2
  • 12
  • 12
  • 1
    You could also do `swap(blocks[x][y], blocks[x+1][y]);`. If you think that looks better, or if you want to be similar to generic code that assumes only a Swappable type. – aschepler Feb 16 '13 at 21:40
  • Is that any better/equals/worse in terms of performance or is it the same as the solution I posted? – bquenin Feb 16 '13 at 21:51
  • Probably identical. But as with any question about performance, the real answer is to try both and compare assembly and/or measure performance. – aschepler Feb 16 '13 at 22:01

1 Answers1

3

sure is. see the documentation for unique_ptr::swap

Thomas
  • 4,980
  • 2
  • 15
  • 30