我正在尝试重构以下代码,这些代码依赖于经典的C样式数组,使其更像C++:
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;
}
}
}
以下代码依赖于std::array
和std::unique_ptr
。我需要像以前的代码一样交换2个值,但我不确定这是否是正确的方法:
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]);
}
}
}
swap
成员是实现这一目标的正确途径吗?
当然是。请参阅unique_ptr::swap 的文档