2014-08-27 65 views
0

我有一个程序正在绘制窗口上不同位置的图像序列。该类有多个实例,但它是在窗口内所有位置绘制的相同图像序列。我想,以防止类的多个实例initializaing多个图像序列,避免吃内存,对此我有静态变量在多个类中使用私有静态变量

class Drawer{ 
private: 
static ImageSequence imgSequence; 
}; 

在.cpp文件中的图像序列变量,我做以下初始化静态变种。

#include "Drawer.h" 

ImageSequence Drawer::imgSequence = ImageSequence(); 

不过,我有两种方法来指定路径图像序列,并预装人框架 - 和困惑在哪里把这些方法使每个抽屉类实例化没有预装帧一次又一次。这是如何在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 
} 
} 
+0

你说*我有两个方法:*。请发布这两种方法的(简化)代码,以便我们能更好地理解你想要的。 – pts 2014-08-27 21:00:32

+0

请注意静态初始化(例如'ImageSequence Drawer :: imgSequence = ImageSequence();')是不安全的,因为翻译单元之间的顺序是不确定的。 – pts 2014-08-27 21:01:27

+0

@pts:大多数情况下,只有当你使用一个'static'对象来初始化另一个'static'对象。不是一个答案,但为什么不在这里使用flyweight模式(如在boost中实现)而不是'static'变量? – 2014-08-27 21:04:01

回答

0

对图像有一个伴随的布尔值,并检查当您尝试加载它时图像是否已经加载。您也可以在程序初始化一次时加载它,而不是每次尝试加载它。

0

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

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

注意这不是线程安全的。使用C++ 11时,'getSequence'中的函数本地'static'变量可以工作(甚至可能适用于某些C++ 98编译器)。 – 2014-08-27 21:06:02

+0

@BenjaminBannier我错过了OP要求代码必须是线程安全的,你能指出它吗? – Slava 2014-08-27 21:09:37

+0

为什么不,如果很简单https://stackoverflow.com/questions/1661529/is-meyers-implementation-of-singleton-pattern-thread-safe? – 2014-08-27 21:16:14