我正在使用来自 stb_image 的原始数据为一个项目编写一个 Image 类。在此类的析构函数中,我将释放指向图像数据的指针以避免内存泄漏。但是,当调用析构函数并释放数据时,我会遇到访问冲突。
图片标题:
class Image {
unsigned char* pixelData;
public:
int nCols, nRows, nChannels;
Image(const char* filepath);
Image(unsigned char* data, int nCols, int nRows, int nChannels);
Image();
~Image();
Image getBlock(int startX, int startY, int blockSize);
std::vector<unsigned char> getPixel(int x, int y);
void writeImage(const char* filepath);
};
Image的构造函数和析构函数:
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image.h"
#include "stb_image_write.h"
#include "image.hpp"
Image::Image(const char* filepath) {
pixelData = stbi_load(filepath, &nCols, &nRows, &nChannels, 0);
assert(nCols > 0 && nRows > 0 && nChannels > 0);
std::cout << "Image width: " << nCols << "\nImage height: " << nRows << "\nNumber of channels: " << nChannels << "\n";
}
Image::~Image() {
stbi_image_free(this->pixelData);
}
最小可重现示例:
int main() {
Image image;
image = Image("./textures/fire.jpg");
}