跨多个类使用私有静态变量
Using private static variable across multiple classes
我有一个程序的类,它在窗口的不同位置绘制图像序列。该类有多个实例,但它是在窗口内所有位置绘制的同一图像序列。我想防止类初始化多个图像序列的多个实例,以避免占用内存,为此我将图像序列变量作为静态变量
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;
}
};
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 模板基类中的静态变量
- 类和静态变量
- 不同作用域中的静态变量和全局变量
- 静态变量声明和定义
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 在类中继承静态变量?
- "local scope"中的 C++ 初始化静态变量
- 使用静态变量的递归调用的不同输出
- 复制文件流C++静态变量
- 跨模板化函数编译的静态变量
- C++编译器是否优化了顺序静态变量读取?
- C++,每个循环初始化一个新的静态变量
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- 程序如何知道静态变量是否需要初始化?
- 类外的静态变量实例化
- 无法解析静态变量
- 函数局部静态变量:从性能角度来看的优点/缺点
- 访问从 CPP 文件到其他头文件的静态变量