c++ - 通过 shared_ptr 访问 calloc 的数据

标签 c++ boost shared-ptr

我正在尝试通过 shared_ptr 访问我之前使用 calloc 方法分配的数据。出于某种原因,我无法在 glTexImage2D(我的代码片段的最后一行)上访问它(继续使用 EXC_BAD_ACCESS 崩溃)。

我加载数据的util方法:

shared_ptr<ImageData> IOSFileSystem::loadImageFile(string path) const
{
    // Result
    shared_ptr<ImageData> result = shared_ptr<ImageData>();

    ...

    // Check if file exists
    if([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:NO])
    {
        ...

        GLubyte *spriteData = (GLubyte*) calloc(width * height * 4, sizeof(GLubyte));

        ...

        // Put result in shared ptr
        shared_ptr<GLubyte> spriteDataPtr = shared_ptr<GLubyte>(spriteData);
        result = shared_ptr<ImageData>(new ImageData(path, width, height, spriteDataPtr));
    }
    else
    {
        cout << "IOSFileSystem::loadImageFile -> File does not exist at path.\nPath: " + path;
        exit(1);
    }

    return result;
}

ImageData 的 header :

class ImageData
{
public:
    ImageData(string path, int width, int height, shared_ptr<GLubyte> data);
    ~ImageData();

    string getPath() const;

    int getWidth() const;
    int getHeight() const;

    shared_ptr<GLubyte> getData() const;

private:
    string path;

    int width;
    int height;

    shared_ptr<GLubyte> data;
};

调用util类的文件:

void TextureMaterial::load()
{
    shared_ptr<IFileSystem> fileSystem = ServiceLocator::getFileSystem();
    shared_ptr<ImageData> imageData = fileSystem->loadImageFile(path);

    this->bind(imageData);
}



void TextureMaterial::bind(shared_ptr<ImageData> data)
{
    // Pointer to pixel data
    shared_ptr<GLubyte> pixelData = data->getData();

    ...

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, data->getWidth(), data->getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixelData);
}

仅作记录:如果我丢弃所有 shared_ptr,我就可以访问数据。 glTexImage2D 的签名:

void glTexImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *data);

附加问题:通常你必须释放(spriteData)但是因为我把数据给了一个 shared_ptr,当 shared_ptr 被移除时数据会被释放吗?

最佳答案

shared_ptr 无法神奇地猜测如何释放内存。默认情况下,它会尝试删除它,并且由于您没有使用new,所以最终会导致灾难。

你需要告诉它怎么做:

shared_ptr<GLubyte>(spriteData, &std::free);

关于c++ - 通过 shared_ptr 访问 calloc 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11777119/

相关文章:

g++ 中的 C++11 语言支持,没有 `-std=c++11` 的库破坏功能

c++ - 我可以仅针对 boost 单元测试失败获得日志输出吗

c++ - boost.mpi 中的自定义 reduce 操作

c++ - 使用 shared_ptr 作为输出参数

c++ - 尝试制作 shared_ptr 时 std::make_shared() 出错?

c++ - std::for_each 和仿函数 - operator() 可以有哪些签名?

c++ - 从 C++ : How to read this specific format? 读取 HDF5 数据

multithreading - 在 Linux SMP 上 boost 线程和不存在的 boost

c++ - 从 weak_ptr 泄漏原始指针的可移植 hack

c++ - glutswapbuffers 实际上做了什么?