I have a std::vector
of Trees, a custom type, and I have a loop which pushes back a tot of Trees to the vector. The problem is: I need push back temporary Tree objects, but, at the same time, I have to avoid them getting deallocated (I thought adding a rvalue reference constructor to the Tree class would have solved the problem, but it didn't).
Tree class:
class Tree
{
public:
Tree();
Tree(Coords, Pixel, Pixel, uint8_t);
Tree(const Tree&);
Tree(const Tree&&);
~Tree();
Tree& operator=(const Tree&);
Tree& operator=(const Tree&&);
void draw();
void chop(uint8_t);
Coords getCoords() const {return log->coords;}
const Log& getLog() const
{
return *log;
}
const Crown& getCrown() const
{
return *crown;
}
private:
Log* log;
Crown* crown;
};
Tree::Tree():
log(nullptr), crown(nullptr)
{
}
Tree::Tree(Coords c, Pixel wd, Pixel lvs, uint8_t h):
log(new Log(c, wd, h)), crown(new Crown({c.x, static_cast<coordsCounter>(c.y + h)}, lvs, getRandBetweenEqu(3, 4)))
{
draw();
}
Tree::Tree(const Tree& tree):
log(new Log(tree.log->coords, tree.log->texture, tree.log->height)),
crown(new Crown(tree.crown->coords, tree.crown->texture, tree.crown->width))
{
draw();
}
Tree::Tree(const Tree&& tree):
log(new Log(tree.log->coords, tree.log->texture, tree.log->height)),
crown(new Crown(tree.crown->coords, tree.crown->texture, tree.crown->width))
{
draw();
}
Tree& Tree::operator=(const Tree& tree)
{
if(log != nullptr) delete log;
if(crown != nullptr) delete crown;
log = new Log(*tree.log);
crown = new Crown(*tree.crown);
return *this;
}
Tree& Tree::operator=(const Tree&& tree)
{
if(log != nullptr) delete log;
if(crown != nullptr) delete crown;
log = new Log(*tree.log);
crown = new Crown(*tree.crown);
return *this;
}
void Tree::draw()
{
log->draw();
crown->draw();
}
Tree::~Tree()
{
chop(0);
}
void Tree::chop(uint8_t h)
{
if(crown != nullptr)
{
delete crown;
crown = nullptr;
}
if(h == 0)
{
if(log != nullptr)
{
delete log;
log = nullptr;
}
} else
{
if(h <= log->height)
{
log->chop(h);
}
}
}
Function pushing back trees:
void growTrees(uint8_t m, uint8_t M)
{
Coords treeCoords;
for(coordsCounter i = 5; i < grid.getMaxXY().x - 4; i += getRandBetweenEqu(m, M))
{
if((treeCoords = getFirstBlock({i, static_cast<coordsCounter>(grid.getMaxXY().y - 1)}, 's', grassTexture) + Coords{0, 1}) != Coords{0, 1})
{
trees.push_back(Tree(treeCoords, woodTexture, leavesTexture, getRandBetweenEqu(minTreeHeight, maxTreeHeight)));
}
}
}