views:

221

answers:

3

I have a PolygonList and a Polygon type, which are std::lists of Points or lists of lists of points.

class Point {
    public:
        int x, y;
        Point(int x1, int y1)
        {
            x = x1;
            y = y1;
        }
};

typedef std::list<Point> Polygon;
typedef std::list<Polygon> PolygonList;


// List of all our polygons
PolygonList polygonList;

However, I'm confused on reference variables and pointers.

For example, I would like to be able to reference the first Polygon in my polygonList, and push a new Point to it.

So I attempted to set the front of the polygonList to a Polygon called currentPolygon like so:

 Polygon currentPolygon = polygonList.front();
 currentPolygon.push_front(somePoint);

and now, I can add points to currentPolygon, but these changes end up not being reflected in that same polygon in the polygonList. Is currentPolygon simply a copy of the Polygon in the front of polygonList? When I later iterate over polygonList all the points I've added to currentPolygon aren't shown.

It works if I do this:

polygonList.front().push_front(somePoint);

Why aren't these the same and how can I create a reference to the physical front polygon rather than a copy of it?

+6  A: 

like this:

 Polygon &currentPolygon = polygonList.front();
 currentPolygon.push_front(somePoint);

the & sign before the name means this is a reference.

shoosh
KingNestor
Ates Goral
Simon Buchan
A: 

You should probably define your list as a list of pointers in the first place:

typedef std::list<Point> Polygon;
typedef std::list<Polygon*> PolygonList;

This avoids much expensive copying. Of course, you will need to do some manual memory management then.

Thomas
I believe most std::list<T>'s implement shallow copy, or at least std::swap().
Simon Buchan
+1  A: 
 Polygon currentPolygon = polygonList.front();

Since the class Polygon does not overload the assignment operator, the compiler silently does this for you and instantiates it at this line.

The default behavior of the assignment operator, implemented in the version thus introduced by the compiler, is to make a copy of the object.

David