C+ delete operator doesn't work properly

Getting an exception thrown error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
#include <vector>
 using namespace std;

class Shape
{
public:
	virtual void Draw() = 0;
	virtual ~Shape() {};
};
class Point
{
public:
	Point() { this->_x = 0; this->_y = 0; }
	Point(int x, int y) :_x(x), _y(y) {}
 
	friend ostream& operator<< (ostream& out, Point const& point)
	{
		return out << "(" << point._x << ", " << point._y << ")";
	}
private:
	int _x;
	int _y;
};
class Polygon : public Shape
{
public:
 
	virtual void Draw() override {};
	  ~Polygon() {}

};

class Line : public Polygon
{
public:
	Line():msize(v->size()) {
 
		v->push_back(Point(0, 0));
		v->push_back(Point(0, 0));
		std::cout << "Line construction" << std::endl; }
	Line(Point pt1, Point pt2):	msize (v->size())
	{ 

		v->push_back(pt1);
		v->push_back(pt2);
		
		std::cout << "Line construction" << std::endl; 
	
	}
	Line(const Line& other)
		: v(other.v),msize(other.msize)
	{
		 
	}
	virtual void Draw() override
	{
		std::cout << "Line drawing" << std::endl;
		
	}
	int size() const
	{
		return v->size();
	}
	friend ostream& operator<< (ostream& stream, const  Line line)
	{
		stream << "Line";
		for (int i{ 0 };i<line.msize ;i++)
		{
			stream << (*line.v)[i]<<" ";
		}
		stream << endl;
		return stream;
	}
  	Line& operator = (const Line& other)
	{
		if (this != &other)
		{
 
			int size = other.msize;
			 
			for (int i = 0; i < other.msize; i++)
			{
				this->v[i] =other.v[i];
			}
 
		}
		return *this;
	}
	~Line()
	{
		delete[]v;
 }
private:
 
	std::vector<Point>* v = new std::vector<Point>[2];
	int msize;
};

 
int main()
{
	Line l1; 				//Output: Line construction
	std::cout << l1; 		//Output: Line (0,0) (0,0)
	l1.Draw(); 				//Output: Line drawing

	Line l2(Point(),
		Point(100, 100));	//Output: Line construction
	std::cout << l2; 		//Output: Line (0,0) (100,100)
	l1 = l2;
	std::cout << l1; 		//Output: Line (0,0) (100,100)

 
	return 0;
} 							 
Last edited on
The problem is on line 89. You make a shallow copy and both pointers point to the same address. That means the second call to delete will try to delete memory that was already deleted and then an exception is thrown.

Ask Google about copy constructors and copy assignment operators and rule of five and deep copy.
Or even better forget about pointers.

Why do you use pointers at all?
In modern C++ there is not so much need for pointers anymore.

You could put both vectors in an array.
1
2
std::vector<Point> v[2];
or std::array<std::vector<Point>, 2>

Topic archived. No new replies allowed.