Using private static variable across multiple clas

2019-08-29 04:07发布

问题:

I've a class for my one of programs which is drawing image sequences at different positions on the window. The class has multiple instances but it's the same image sequence which is being drawn at all the positions inside the window. I want to prevent multiple instances of class initializaing multiple image sequences to avoid eating memory, for which I have the image sequence variable as static variable

class Drawer{
private:
static ImageSequence imgSequence;
};

In the .cpp file, I am doing the following to initialize the static var.

#include "Drawer.h"

ImageSequence Drawer::imgSequence = ImageSequence();

However, I have two methods to specify the path to image sequences and preload al frames - and confused about where to put these methods so that each Drawer class instantiation does not preload the frames time and again. How'd this be done in C++?

--EDIT The two methods as asked for: i) loadSequence, ii)preloadAllFrames();

    loadSequence(string prefix, string firstFrame, string lastFrame){
    for(int i=0;i<numFrames;++i){
    //adds and pushes values of all the files in the sequence to a vector
    }
}

preloadAllFrames(){
for(int i=0;i<numFrames;++i){
//create pointers to image textures and store then in a vector so that it doesn't take time to load them for drawing
}
}

回答1:

Have an accompanying boolean value with the image and check if the image has been already loaded when you try to load it. You can also load it when your program is initializing only once instead of attempting to load it every frame.



回答2:

Just have a static pointer instead of instance and initialize in a static method:

class Drawer{
private:
    static std::unique_ptr<ImageSequence> imgSequence;
public:
    static void initializeMethod1() 
    {
        if( imgSequence ) return; // or throw exception
        imgSequence.reset( new ImageSequence( ... ) );
        ...
    }

    static void initializeMethod2() {}
    {
        if( imgSequence ) return; // or throw exception
        imgSequence.reset( new ImageSequence( ... ) );
        ...
    }

    static ImageSequence &getSequence() 
    { 
        if( !imgSequence ) throw std::runtime_error( "image sequence is not intialized" );
        return *imgSequence;
    }
};


标签: c++ oop static