In the following code snippet, the Line destructor gets called twice, causing a double free issue. I have 2 questions here:
- I noticed that changing the code to:
Line pCopy = pLine->deep_copy();
fixes the issue, but I'm still not clear what causes the difference. - If I implement a copy constructor in Line class, and using the fix explained in "1", the copy constructor gets called instead of the desired deep_copy() function. What is the reason for this behavior and are there any workarounds?
struct Point
{
int x{ 0 }, y{ 0 };
Point(){}
Point(const int x, const int y) : x{x}, y{y} {}
};
struct Line
{
Point *start, *end;
Line()
: start{nullptr}, end{nullptr}
{
}
Line(Point* const start, Point* const end)
: start(start), end(end)
{
}
~Line()
{
delete start;
delete end;
}
Line deep_copy() const
{
Point* p1 = new Point{*start};
Point* p2 = new Point{*end};
return { p1, p2 };
}
};
int main()
{
Point* start = new Point{1,2};
Point* end = new Point{1,2};
Line* pLine = new Line{start, end};
Line pCopy;
pCopy = pLine->deep_copy();
pCopy.start->x = 3;
pCopy.start->y = 4;
}
Edit: Please assume that the Line class has to store pointers to Point objects instead of storing the entire object inside it.