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?