跨多个类使用私有静态变量

Using private static variable across multiple classes

本文关键字:静态 变量      更新时间:2023-10-16

我有一个程序的类,它在窗口的不同位置绘制图像序列。该类有多个实例,但它是在窗口内所有位置绘制的同一图像序列。我想防止类初始化多个图像序列的多个实例,以避免占用内存,为此我将图像序列变量作为静态变量

class Drawer{
private:
static ImageSequence imgSequence;
};

在.cpp文件中,我正在执行以下操作来初始化静态var.

#include "Drawer.h"
ImageSequence Drawer::imgSequence = ImageSequence();

然而,我有两种方法来指定图像序列的路径和预加载所有帧,并且混淆了将这些方法放在哪里,这样每个Drawer类实例化就不会一次又一次地预加载帧。在C++中是如何做到这一点的?

--编辑要求的两种方法: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
}
}

在图像中附带一个布尔值,并在尝试加载图像时检查图像是否已加载。您也可以在程序仅初始化一次时加载图像,而不是尝试每帧加载一次。

只需要一个静态指针而不是实例,并在静态方法中初始化:

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;
    }
};