Hm.. ok, yea.. didn't spot the return-by-value. So what happens is this:
|
*CurrTriangle2 = *CurrTriangle1;
| |
First, the assignment operator will be called on the object of CurrTriangle2 with the parameter of CurrTriangle1.
But within this assignment operator, the last statement "return *this;" will call the non-existing copy constructor of your Triangle class to copy the *this into a new temporary variable (since you returned by value). Since your copy-constructor is not specified, it generates a default one that just
assign all members. So the temporary variable hods a pointer to the
same origNormal than *this, which is the CurrTriangle2 - object.
This new and temporary variable is discarded immediately since line 61 don't use the return value. Discarding also means its destructor is called, freeing the same origNormal that CurrTriangle2 is pointing to. Voila.
You can fix this by implementing your own copy constructor. But I rather suggest you think about whether you really need a pointer to the Normal - class or whether a normal non-pointer object will do it. Because then you don't need all the hassle you have at the moment with allocating, destructing, copying around blabla.. the default operator= and default copy-constructor will do just fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
class Normal // define before Triangle, as now Triangle depends on the complete type
{
public:
double nx,ny,nz;
double angle;
Normal()
{
nx=0.0,ny=0.0,nz=0.0;
angle = 0.0;
}
// no CopyToNormal needed
};
class Triangle
{
public:
long int ID;
Normal origNormal; // no pointer. Just normal object
Triangle()
{ID=0;}
// no destructor needed
// no own operator= needed
// no copy constructor needed
};
| |
Plain, simple, straight-forward.
If you can't live with this (e.g. because you need polymorphism or you don't have the complete type of Normal in the header of Triangle), you can consider using one of the smart pointers like shared_ptr, unique_ptr or auto_ptr.
Ciao, Imi.