Imagine the simple class line segment which it’s constructor is are couple of objects from the class point:
class Point ;
class LineSegment {
public:
LineSegment(Point* P1, Point* P2);
~LineSegment();
} ;
The question is, in the destructor, should I delete the points first or it will be done automatically? On the other words, in the cpp file, which of the following should be written:
LineSegment::~LineSegment()
or
LineSegment::~LineSegment(){
delete P1;
delete P2;
}
First, note that
is invalid. To delete, you need
delete P1anddelete P2.Also, figure out who owns
P1andP2. If they are owned by the class, delete them in the destructor, but note that you won’t be able to access them outside after the object is destroyed.So, for example:
Would be illegal if you
deletethe pointers in the destructor.Either version you choose, be sure to document your decision – i.e. make it clear whether the class assumes ownership of the pointers or not.
You wouldn’t have this problem if you’d use smart pointers.