这不是作业,只是关于我的代码的问题(我正在学习 C++)。
我有该类的多个实例,Renderer
它们都使用相同的资源,即由 SDL 加载的 BMP。这是管理班级共享资源的正确方法吗?如果没有,什么是好的?如果是,有更好的吗?
渲染器.hpp
class Renderer {
public:
Renderer(SDL_Surface *target_surface, int w, int h);
Renderer(const Renderer& renderer);
~Renderer();
// ...
private:
int w, h;
SDL_Surface *target;
static SDL_Surface *blocks;
static int numinstances;
};
渲染器.cpp
const char BLOCKS_FILE[] = "blocks.bmp";
SDL_Surface *Renderer::blocks = 0;
int Renderer::numinstances = 0;
Renderer::Renderer(SDL_Surface *target, int w, int h) {
numinstances++;
if (blocks == 0) {
// temporary storage for file
SDL_Surface *loadedimg = SDL_LoadBMP(BLOCKS_FILE);
if (loadedimg != NULL) {
blocks = SDL_DisplayFormat(loadedimg);
SDL_FreeSurface(loadedimg);
}
}
this->target = target;
this->w = w;
this->h = h;
}
Renderer::Renderer(const Renderer& renderer) {
numinstances++;
w = renderer.w;
h = renderer.h;
target = renderer.target;
}
Renderer::~Renderer() {
numinstances--;
if (numinstances == 0) {
SDL_FreeSurface(blocks);
blocks = 0;
}
}