Class Destructor gets called too soon?

Hi,
I have a class slide which contains among other things a pointer to an ofImage which is later loaded via ofxThreadedImageLoader.

  
ofImage * thisPicture;  

My constructor and destructor look like this:

  
    slide() {   
        thisPicture  = new ofImage();  
    }  
    ~slide() {  
        delete thisPicture;  
    }  
  

I also have another version of the destructor which checks if ofxThreadedImageLoader is still accessing thisPicture, but I left it out here, because I think I have a more fundamental problem.
I have a slideManager class which contains among other things a vector of Objects.
I fill it like this:

  
        thisPadsSlides.push_back(slide());  
        [...]  
        loader.loadFromDisk(thisPadsSlides.back().thisPicture, DIR.getPath(directoryCounter));  
  
        loader.startThread(false, false);   

If I keep track of what’s happening, the constructor gets called first but right after it the destructor gets called. Before the loader even starts. So basically the loader is trying to access memory that’s already freed. I thought, the destructor would be called after I earase a slide object from the vector. But obviously I was wrong. What do I miss?

im not sure if this is your problem but you should know the following internal vector behaviour:
every time when you push_back() in your vector it is possible, that the reserved space for your vector is full. in this case space twice the size will be reserved und all objects get copied to the new space and erased at the old. so every time your vector needs more space copyconstructor and descructor will be called for each element.

in your case your destructor deletes the ofImage and so every copied slide tries to access a freed image.

an easy and fast workarround would be to reserve more space for your vector in the setup() but in a dynamic system this will only postpone your “bad access” in time. better use list instead of vector!

Hi,
thanks for the reply. I did know about the resize and I did reserve enough space though.
I think this is the problem: http://stackoverflow.com/questions/8543854/when-adding-an-element-to-a-vector-how-to-know-that-a-copy-of-the-object-is-goi

yes, but it’s more or less the same problem. your orginal slide (created by slide() ) gets deleted (after push_back()) and so the image of your copied slide is freed. you should work with a vector of pointers of slides (or make sure that your orginal slide lives long enough).