I ran into a lack of deep understanding of C ++ pointers. I wrote a class called Skymap, which has the following definition:
class Skymap { public: Skymap(); ~Skymap(); void DrawAitoffSkymap(); private: TCanvas mCanvas; TBox* mSkymapBorderBox; };
with functions defined as:
#include "Skymap.h" Skymap::Skymap() { mCanvas.SetCanvasSize(1200,800); mMarkerType=1; } Skymap::~Skymap() { delete mSkymapBorderBox; } void Skymap::DrawAitoffSkymap() { TBox* mSkymapBorderBox=new TBox(-200,-100,200,100);
(I use the ROOT build package, but I think this is just a general C ++ question).
Now the following program will crash when the skymap2 destructor is reached:
int main(){ Skymap skymap1; Skymap skymap2; skymap1.DrawAitoffSkymap(); skymap2.DrawAitoffSkymap(); return(0); }
However, the following will not crash:
int main(){ Skymap skymap1; skymap1.DrawAitoffSkymap(); return(0); }
Also, if I initialize the mSkymapBorderBox pointer to NULL in the constructor, I no longer crash after executing the first program (with two Skymap objects).
Can someone explain what is the main reason for this? There seems to be a problem with the pointer in the second Skymap object, but I don't see what it is.
source share