首页 > 解决方案 > 从包装类中的 stb_image 释放图像数据的问题

问题描述

我正在使用来自 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");
}

标签: c++stb-image

解决方案


默认复制构造函数会导致双重释放。有两种方法可以解决它 -

  1. 您可以使用具有自定义删除器的 unique_ptr 包装资源,这将使该类无论如何都只能移动。
  2. 或者,明确地使其不可复制。

推荐阅读