我在课堂上有一个动态数组。我有两个问题:
- 我想知道如何为动态数组编写移动构造函数和移动赋值运算符
Tile* mytiles
? - 数组如何写为智能指针
uni_ptr
?这是代码:
class Grid
{
private:
size_t _rows_;
size_t _cols_;
Tile _initialTile_;
Tile* mytiles;
public:
// Tile is a self defined class
Grid(size_t rows, size_t cols, const Tile &initialTile): _rows_(rows),
_cols_(cols),
_initialTile_(initialTile)
{
mytiles = new Tile[_cols_ * _rows_];
std::fill(&(mytiles[0]), &(mytiles[0]) + (_rows_ *
_cols_sizeof(Tile)),_initialTile_);
}
Grid(const Grid &other): _rows_(other._rows_), _cols_(other._cols_),
_initialTile_(other._initialTile_)
{
mytiles = new Tile[other._rows_ * other._cols_];
std::copy(other.mytiles, other.mytiles + other._rows_ * other._cols_, mytiles);
}
Grid::operator=(const Grid &other)
{
if (this == &other)
{
return *this;
}
_rows_ = other._rows_;
_cols_ = other._cols_;
_initialTile_ = other._initialTile_;
mytiles = new Tile[other._rows_ * other._cols_];
std::copy(other.mytiles, other.mytiles + other._rows_ * other._cols_, mytiles);
}
Grid(Grid &&other) noexcept: _rows_(std::move(other._rows_)),
_cols_(std::move(other._cols_)),
_initialTile_(std::move(other._initialTile_)),
mytiles(std::move(other.mytiles))
{
other.mytiles = nullptr;
}
Grid::operator=(Grid &&other) noexcept
{
_rows_= std::move(other._rows_);
_cols_= std::move(other._cols_),
_initialTile_= std::move(other._initialTile_);
delete[] mytiles;
mytiles = std::move(other.mytiles);
other.mytiles = nullptr;
return *this;
}
};
Tile
是一个枚举:
enum Tile {
See, Sky, Road
};
Tile tile_from_char(const char &c);
char char_from_tile(const Tile &t);
感谢您的时间和帮助。