I made a minimal example:
#include <iostream>
#include <conio.h>
using namespace std;
// skipped getters and setters and bounds checking for brevity
struct Vertex {
int x,y;
Vertex() {
}
Vertex(int x, int y) {
this->x = x;
this->y = y;
}
};
struct Polygon {
Vertex *vertexlist;
Polygon() {
}
Polygon(Vertex *v) {
vertexlist = new Vertex[4]; //hard coded 4 vertices for example brevity
for(int i=0;i<4;i++) {
vertexlist[i] = v[i];
}
}
Vertex& getVertex(int index) const {
return this->vertexlist[index];
}
};
struct PolyList {
Polygon *polylist;
int lastpoly;
PolyList() {
polylist = new Polygon[10]; //hard coded 10 for example brevity
lastpoly = 0;
}
void add(const Polygon& p) {
polylist[lastpoly++] = p;
}
};
ostream& operator<<(ostream& o, Vertex& v) {
return o << "(" << v.x << ", " << v.y << ")";
}
ostream& operator<<(ostream& o, const Polygon& p) {
for(int i=0;i<4;i++) {
o << p.getVertex(i) << ", ";
}
return o;
}
ostream& operator<<(ostream& o, PolyList& pl) {
for(int i=0;i<pl.lastpoly;i++) {
o << pl.polylist[i] << endl;
}
return o;
}
int someFunc() {
Vertex *vl = new Vertex[4];
PolyList pl;
vl[0] = Vertex(1,2);
vl[1] = Vertex(3,4);
vl[2] = Vertex(5,6);
vl[3] = Vertex(7,8);
pl.add(Polygon(vl)); // this Polygon goes out of scope after this line
cout << pl << endl;
}
int main() {
someFunc();
}
(So tl;dr, Polygon
is a list of 4x Vertex
, and PolyList
is a list of Polygon
:s. Polygon
:s are add()
ed to PolyList
by instantiating a temporary Polygon
)
Now, this leaks memory, because the Vertices in Polygon
are never freed. However, if I add a destructor:
Polygon::~Polygon () {delete [] vertices}
then
cout << pl << endl;
will not work because the Polygon
has gone out of scope and the destructor frees the vertices.
I could have the PolyList
destructor call a Polygon->free()
function. Alternatively, I could have the Polygon::Polygon(Vertex *v)
deep copy all the vertices in v. Then PolyList::PolyList(Polygon &p)
could deep copy p.
I could also make a PolyList::createPolygon(int x1, int y1, int x2, int y2...)
but that flies in the face of OO.
What is the proper way to handle this kind of situation in C++? Never mind my actual example where a memory leak would not be a problem, I'm talking in principle. If I make an hierarchical object tree, I want to copy the pointers, not deep copy the objects.
EDIT: I'm trying to learn C++ on a deep level, so this is not about using vector<> or another "canned solution"; that is not what I'm after here, though I'm sure that is a good solution if the above example was an actual problem I was having. The example above is just the briefest example I could think of to explain my question.