I have ventured into class hierarchies in my OpenGL adventure. At the top is the “Shape” class, which knows how to supply a list of vertices and colors for OpenGL to consume. Then there is the “Cube” subclass, which, as the name implies, is a cube.
Using my old C/C++ instincts intertwined with newfangled C++, I declared my vector of objects like this:
std::vector<std::unique_ptr<Shape>> shapes(2); // only 2 shapes so far
And then I filled in the array like this (my cube constructor takes a vector as initial position):
shapes[0] = std::make_unique<Cube>(glm::vec3(1.5, 0, 0));
shapes[1] = std::make_unique<Cube>(glm::vec3(-1.5, 0, 0));
I wanted to be super modern, so I tried iterating over it like this:
for (auto const shape : shapes)
{
// do stuff with the shape
}
But I got another one of those gibberish warnings about a deleted function. It turns out, unsurprisingly enough, that every time an element of shapes
is assigned to shape
, it thinks someone is trying to steal a unique_ptr
. However, there’s a handy little solution:
for (auto const& shape : shapes)
{
// do stuff with the shape
}
The &
operator was always kind of mysterious to me, like it’s kind of faking a pointer but not really. But I am going to try not to think about it too hard, and just accept that this works. Apparently using a reference does not amount to stealing.
It turns out I could have done this whole thing differently with initializers! But that is for another day. Probably tomorrow.