1

I have some problem with coming up with idea how to design objects copying in my application due to the pointers issue in one of the objects. Simplest schema looks like this:

MyMapClass.h

class MyMapClass
{
    public:
        std::vector<Point> points;
        std::vector<Road> roads;

        MyMapClass& operator=(const MyMapClass&);
}

MyMapClass.cpp

MyMapClass& MyMapClass::operator=(const MyMapClass& m)
{
    points = m.points;
    roads = m.roads; // here is error
    return *this;
}

Point.h

class Point
{
    public:
        std::string name;
        std::vector<float> position;
}

Road.h

class Road
{
    public:
        Point* source;
        Point* destination;
}

Originally it was designed without need to copy MyMapClass object and it took me a while to spot that error.

As I understand now, when I am copying both vectors to new objects addresses in elements of roads to source and destination stays this same. So when the old object is destroyed the pointers in roads elements just point to garbage.

How would you recommend copying also roads vector so that it's elements will point to new objects?

sebap123
  • 2,541
  • 6
  • 45
  • 81

2 Answers2

1

If you can, use objects of type Point instead of Point* in Road.

class Road
{
    public:
        Point source;
        Point destination;
};

If you must use pointers, follow The Rule of Three.

Also, if you must use pointers, consider using smart pointers, std::shared_ptr or std::unique_ptr, instead of raw pointers.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Just create a copy constructor for class Road ... The copy assignment of std::vector will invoke the copy constructor of each element....

class Road
{
    public:
        Point* source;
        Point* destination;
        Road(const Road& r) { /* implement copy operations of source and destination here */ }
}

Then the assignment here will invoke the above copy constructor in creating all the new elements

MyMapClass& MyMapClass::operator=(const MyMapClass& m)
{
    points = m.points;
    roads = m.roads; // invokes copy constructor m.roads.size() times
    return *this;
}
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
  • I was thinking about it, but will it know the new address of points? – sebap123 Apr 01 '16 at 17:56
  • Yes, it will... provided your copy constructor for `class Road` makes `source` and `destination` point to new locations – WhiZTiM Apr 01 '16 at 18:21
  • Yes I know about that. But my concern is - if `source` and `destination` point to one place in memory, and with `points = m.points` new objects are created, `source` and `destination` still points to old places in memory. And they have no clue that some change has happened. – sebap123 Apr 01 '16 at 18:25